1

Thanks for checking out my question. I am trying to only update a value in my database if that field is null (so existing users won't be overwritten if someone tries to signup for a spot that is all ready taken and an error message will be output). I have listed below 2 of the most recent scripts I have tried. The first script works for updating the database if the select statement is not there but will overwrite users if entered for the same day and time. Thanks everybody!

$sql = ("SELECT `player1` FROM `users` where id = '$id' and Times = '$time'"); 


$result = $conn->query($sql);

if ($result->fetch_assoc === NULL) {
$update_player = ("UPDATE users SET player1 = '$name' where id = '$id' AND Times =   '$time'")

if($update_player){
echo "Date for $name inserted successfully!";
}
}

else {
  echo 'That spot is all ready taken!';
}

//2nd script 

$query=mysql_query("UPDATE users SET 
player1 = isNULL (player1, $name) 
where id = '$id' AND Times = '$time'" );

if($query){

 echo "Data for $name inserted successfully!";
}

else {
 echo 'That spot is all ready taken!';
}
2
  • I think you forgot to say what your problem is. BTW, use pdo or mysqli_* instead of mysql_* because the last one is deprecated and won't be supported in future. Commented Dec 27, 2012 at 14:56
  • Maybe the NULL information should be a condition in your query. Try some deeper tests in an SQL interface. Commented Dec 27, 2012 at 15:12

2 Answers 2

2

The following code should do the trick:

$query=mysql_query("UPDATE users SET 
player1='$name' 
where id = '$id' AND Times = '$time' AND player1 IS NULL" );

if(mysql_affected_rows() == 1){
  echo "Data for $name inserted successfully!";
}
else {
  echo 'That spot is all ready taken!';
}

Note that you should use pdo or mysqli functions instead.

Sign up to request clarification or add additional context in comments.

Comments

0

Try This.

 while($row = $result->fetch_assoc) {
    if($row['player1'] == NULL){
      $update_player = ("UPDATE users SET player1 = '$name' where id = '$id' AND Times =   '$time'")
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.