copilot0910
copilot0910

Reputation: 431

MySQL Update Not Working With If Statement

I'm using AJAX and JSON to update my database, but the values in the database aren't updating.

I know the correct values are getting sent, and also that the correct values are getting returned, but my MySQL update isn't doing anything. It's inside an if statement.

PHP

$youruname = mysql_real_escape_string($_POST['youruname']);
$selectedplayer = mysql_real_escape_string($_POST['selectedplayer']);

$flag = "";
$itStatus = "";

$checkit = mysql_query("SELECT it FROM login WHERE uname='$selectedplayer'");

while($row = mysql_fetch_array($checkit))
{
    $itStatus = $row['it'];
}

if($itStatus === "not it")
{
    mysql_query("UPDATE login SET it='not it' WHERE uname = '$youruname'");
    mysql_query("UPDATE login SET it='it' WHERE uname = '$selectedplayer'");

    $flag = "success";
}
else if($itStatus === "it")
{
    $flag = "nope";
}
else
{
    $flag = "error";
}


echo json_encode(array("message" => $flag, "tagged" => $selectedplayer));

Upvotes: 0

Views: 94

Answers (2)

copilot0910
copilot0910

Reputation: 431

Ok, so I figured it out.

I was making the call to the DB trying to select a value that didn't exist.

Basically, I was searching for the wrong value.

My code is correct.

And to everyone who offered help, thank you.

Upvotes: 0

John Woo
John Woo

Reputation: 263893

This may not be part of your question but instead of executing two update statement, you can make it into one,

UPDATE login SET it='not it' WHERE uname = '$youruname'
UPDATE login SET it='it' WHERE uname = '$selectedplayer'

into

UPDATE login 
SET it = CASE WHEN uname = '$youruname' THEN 'not it' ELSE 'it' END
WHERE uname IN ('$youruname', '$selectedplayer')

Upvotes: 1

Related Questions