我想要某种错误处理,如果语句以错误执行,则设置布尔变量false 或者如果它没有错误地运行,则设置布尔值为真
在我的情况下,我的代码是
$response = array();
$response["success"] = true;
$statement = $mysqli->prepare("INSERT INTO userft (name, username, pasword, email, contact, age) VALUES (?, ?, ?, ?, ?, ?)");
$statement->bind_param('ssssii', $name, $username,$pasword,$email,$contact, $age);
$statement->execute();
if(!($statement->execute())){ //<----- in replace of this statement?<-----
$response["success"]=false;}
答案 0 :(得分:3)
如果将execute
语句返回值分配给变量,则可以测试成功/失败。
$response = array('success'=>false);
$stmt = $mysqli->prepare("INSERT INTO userft (name, username, pasword, email, contact, age) VALUES (?, ?, ?, ?, ?, ?)");
/* First test that the statement was prepared successfully */
if( $stmt ){
$stmt->bind_param('ssssii', $name, $username,$pasword,$email,$contact, $age);
/* assign return value of execute to a variable */
$status = $stmt->execute();
/* use variable to determine response */
$response["success"]=$status ? true : false;
}
上详细了解PHP site
答案 1 :(得分:1)
execute语句返回boolean,所以你做的是正确的事;您可以将结果分配给变量:
$success = $statement->execute();
if ($success) {
echo "Inserted!";
} else {
echo "Something went wrong!";
}
如有疑问,请查看documentation。
答案 2 :(得分:1)
试试这个
$statement->execute();
if ($statement->affected_rows()) {
//success
} else {
die('execute() failed: ' . $mysqli->error);
}