Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The right way to check whether mysqli query was successful

I've read several articles about the problem like this however none of them helped me and I am a bit confused what to do.

Basically, I want 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?
}
like image 674
0101 Avatar asked Oct 21 '22 18:10

0101


1 Answers

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.

like image 150
Sverri M. Olsen Avatar answered Oct 27 '22 10:10

Sverri M. Olsen