在准备好的陈述上回答正确或错误

时间:2012-09-01 04:53:26

标签: php mysqli

我刚刚开始学习mysqli(20分钟前),我对某些事感到困惑。在下面的示例中,我可以将数据插入服务器。如何使函数在成功时返回true,在失败时返回false。如果if语句为真,并且在else语句中为return true,或者它是否比那更高级,那么它就像替换return false一样简单吗?如果我想在成功时返回true而在失败时返回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;
    }}

1 个答案:

答案 0 :(得分: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;
}