$stmt->execute() : How to know if db insert was su

2020-01-29 06:11发布

With the following piece of code, how do i know that anything was inserted in to the db?

if ($stmt = $connection->prepare("insert into table (blah) values (?)")) {
$stmt->bind_param("s", $blah);  
$stmt->execute();           
$stmt->close();                                 
}

I had thought adding the following line would have worked but apparently not.

if($stmt->affected_rows==-1){$updateAdded="N"; echo "failed";}  

And then use the $updatedAdded="N" to then skip other pieces of code further down the page that are dependent on the above insert being successful.

Any ideas?

标签: php oop mysqli
6条回答
Luminary・发光体
2楼-- · 2020-01-29 06:31

You can check the returned value after the execute :

if ($stmt->execute()) { 
    // ok :-)
    $count = $stmt->rowCount();
    echo count . ' rows updated properly!';
} else {
    // KO :-(
    print_r($stmt->errorInfo());
}
查看更多
Bombasti
3楼-- · 2020-01-29 06:37

if you mean that you want to know the number of affected rows you can use rowCount on the pdo statement

$stmt->rowCount();

after execute;

if you are talking about error handling I think the best option is to set the errmode to throwing exteptions and wrap everything in a try/catch block

try
{
    //----
}
catch(PDOException $e)
{
    echo $e->getMessage();
}
查看更多
我欲成王,谁敢阻挡
4楼-- · 2020-01-29 06:43

The execute() method returns a boolean ... so just do this :

if ($stmt->execute()) { 
   // it worked
} else {
   // it didn't
}
查看更多
你好瞎i
5楼-- · 2020-01-29 06:45

Just check the manual pages of whatever function you are using:

prepare() - returns a statement object or FALSE if an error occurred.
bind_param() - Returns TRUE on success or FALSE on failure.
execute() - Returns TRUE on success or FALSE on failure.
close() - Returns TRUE on success or FALSE on failure.

In practice, though, this gets annoying and it's error prone. It's better to configure mysqli to throw exceptions on error and get rid of all specific error handling except for the few occasions where an error is expected (e.g., a tentative insert that might violate a unique constraint):

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
查看更多
欢心
6楼-- · 2020-01-29 06:45

Other way:

if ($stmt->error){
        echo "Error";
    }
    else{
        echo "Ok";
    }
查看更多
Ridiculous、
7楼-- · 2020-01-29 06:48

Check the return value of $stmt->execute()

if(!$stmt->execute()) echo $stmt->error;

Note that line of code does perform the execute() command so use it in place of your current $stmt->execute() not after it.

查看更多
登录 后发表回答