Php, not getting any errors yet this code wont update database

Associate
Joined
11 Oct 2008
Posts
268
Hey guys, can anyone see what i have done wrong on this code, instead of updating my database it just does nothing at all, no errors, no noting.

PHP:
if ($enemy_hp <= 0) {

$sql = "UPDATE game_status SET battle = '1' WHERE id=1";

} else {

$sql = "UPDATE game_character SET current_hp = (current_hp-100) WHERE id=1";


    $statement = $dbh->prepare($sql); 
    $statement->execute();

}
 
From your code, you are only executing the query if the else block is triggered.

If you enter the if condition block then you only set $sql and never run the query.
 
Cant you just do this and execute it after the condition:

Code:
$sql = "";

if ($enemy_hp <= 0) { 
$sql = "UPDATE game_status SET battle = '1' WHERE id=1"; 
} 

else { 
$sql = "UPDATE game_character SET current_hp = (current_hp-100) WHERE id=1"; 
}

echo $sql;
$statement = $dbh->prepare($sql);  
$statement->execute();
 
Last edited:
Something is wrong with the value of $enemy_hp then, the logic is correct. I suggest echoing out the value of it before the condition check.
 
Cant see anything wrong with the variable, its echo'ing fine, maybe I should look at it tomorrow with fresh eyes.

Thanks for your help :)

So it's echo'ing the correct query but executing the first?
Try replacing the SQL string with the prepare function and seeing that makes a difference (shouldn't if the IF statement is working correctly ie: the $SQL is being echoed correctly) -
Code:
if ($enemy_hp <= 0) { 
$statement = $dbh->prepare("UPDATE game_status SET battle = '1' WHERE id=1"); 
} else { 
$statement = $dbh->prepare("UPDATE game_character SET current_hp = (current_hp-100) WHERE id=1"); 
}
$statement->execute();
 
I have slightly extended the code to maybe help you.

PHP:
$dsn		= '';
$user 		= '';
$pass		= '';
$enemy_hp 	= 5;

if ($enemy_hp <= 0) 
{
	$sql = "UPDATE game_status 
		SET battle = '1' 
		WHERE id = 1";
} 
else 
{
	$sql = "UPDATE game_character 
		SET current_hp = (current_hp-100) 
		WHERE id = 1";
}

try
{
	$dbh = new PDO("$dsn", "$user", "$pass");
	$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	$statement = $dbh->prepare($sql); 
        $statement->execute();
        if ($statement->rowCount() < 1)
        {
                   //i suspect you may want to handle this.
        }
}
catch(PDOException $e)
{
	$msg = $e->getMessage();
        echo $msg;
        log($msg);
}
 
Last edited:
Back
Top Bottom