user1930624
user1930624

Reputation: 13

Update value only if Null php/mysql

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!';
}

Upvotes: 1

Views: 5618

Answers (2)

rizon
rizon

Reputation: 8197

Try This.

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

Upvotes: 0

tmuguet
tmuguet

Reputation: 1165

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.

Upvotes: 2

Related Questions