0101 0101 - 7 months ago 124
PHP Question

The right way to check if mysqli query was success

I have read several articles about this problem however none of them helped me and I am quite confused what to do.

Basically, I need to check whether the sql query performed without any errors. To do that, do I have to use both of the if statements shown below?

if($stmt = $mysqli->prepare("INSERT INTO table VALUES (?, ?, ?);"))
{
$stmt->bind_param("sss", $a, $b, $c);

if(!$stmt->execute())
{
// Do I have to catch the problem here?
}

if($stmt->affected_rows === -1){
// Do I have to catch the problem here?
}

$stmt->close();
}
else
{
// Do I need to catch the problem here?
}

Answer

You should check the return values of prepare(), bind_param() and execute(). They all return false if they fail.

If execute() does not return false then the INSERT should have gone through successfully, and therefore checking affected_rows only makes sense if you want to know how many rows were affected.

Comments