0

我刚开始学习 mysqli(20 分钟前),我对某些事情感到困惑。在下面的示例中,我能够将数据插入服务器。我如何使函数在成功时返回 true,在失败时返回 false。是否像替换return trueif 语句为真和return falseelse 语句一样简单,还是比这更高级?如果我想在成功时返回真而在失败时返回假,我必须写什么?

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;
    }}
4

1 回答 1

1

当您使用 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;
}
于 2012-09-01T06:24:28.333 回答