我刚开始学习mysqli(20分钟前),我对一些事情感到困惑。在下面的示例中,我可以将数据插入到服务器中。如何使函数在成功时返回true,在失败时返回false。如果if语句为true,那么它是像替换上的return true
和替换else语句上的return false
一样简单,还是比这更高级?如果我想在成功时回归真,在失败时回归假,我该写什么?
function insert($firstName, $lastName) {
if ($stmt = $mysqli->prepare("INSERT INTO CodeCall (FirstName, LastName) values (?,
?)")) {
/* Bind our params */
$stmt->bind_param('ss', $firstName, $lastName);
/* Execute the prepared Statement */
$stmt->execute();
/* Echo results */
echo "Inserted {$lastName},{$firstName} into database'n";
/* Set our params for second query */
$firstName = "John";
$lastName = "Ciacia";
/* Execute second Query */
$stmt->execute();
return true;
/* Close the statement */
$stmt->close();
}
else {
/* Error */
return false;
}}
使用execute方法执行INSERT查询(以及UPDATES和DELETES查询)时,成功时返回TRUE,失败时返回FALSE。所以你可以这样做:
function insert($firstName, $lastName) {
$stmt = $mysqli->prepare("INSERT INTO CodeCall (FirstName, LastName) values (?, ?)");
/* Bind our params */
$stmt->bind_param('ss', $firstName, $lastName);
/* Execute the prepared Statement */
if ( $stmt->execute() ) {
/* Echo results */
echo "Inserted {$lastName},{$firstName} into database'n";
/* Set our params for second query */
$firstName = "John";
$lastName = "Ciacia";
/* Execute second Query */
$stmt->execute();
$result = true;
} else {
/* Error */
$result = false;
}
/* Close the statement */
$stmt->close();
return $result;
}