如何确定何时在数据库中成功输入表单数据?

时间:2015-03-28 10:08:28

标签: php html mysql pdo

首先是我的代码:

<?php 
//establish connection to the database
require("database.php");
try{
  // prepare and bind
$stmt = $conn->prepare("INSERT INTO clients (phonenumber, firstname) VALUES (:phonenumber, :firstname)");
$stmt->bindParam(':phonenumber', $phonenumber, PDO::PARAM_STR);
$stmt->bindParam(':firstname', $firstname, PDO::PARAM_STR);

 // set parameters and execute
if(isset($_POST['phonenumber'])){ $phonenumber = $_POST['phonenumber']; }
if(isset($_POST['firstname'])){ $firstname = $_POST['firstname']; }
$stmt->execute();

}catch (Exception $e) {
        echo "Could not insert data into the database $e";
        exit;
        }
//my attempt on checking if the data has been successfully entered in the database
        $inserted = true;
?>

<h2>The Form</h2>
<hr />
<br />
<form action="" method="post">
Number: <input type="text" name="phonenumber" value="" />
<br /><br />
First Name: <input type="text" name="firstname" value="" />
<br /><br />
<input type="submit" name="submit" value="Submit">
</form>
<br />
<hr />

</body>
</html>

然后我正在尝试检查表单数据是否已成功输入:

<?php 
if($inserted = true){ 
echo "THE DATA HAS BEEN SUCCESSFULLY ENTERED IN THE DATABASE"; 
}
?>

现在您可以看到我在输入数据时尝试将名为$ inserted的变量设置为true,以便我可以确定数据是否已成功输入。但由于某种原因它不起作用。它一直给我一个$inserted未定义的错误,所以我用isset()包装它,即使它摆脱了错误,但它没有检查是否设置了$inserted。换句话说,即使由于某种原因,我总是不断收到已成功输入的回信消息。

非常感谢帮助,非常感谢。

1 个答案:

答案 0 :(得分:2)

您可以使用->lastInsertId方法检查上次插入是否成功,而不是使用标记。

<?php 

if(isset($_POST['firstname'], $_POST['phonenumber'])) {
    require('database.php');
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $phonenumber = $_POST['phonenumber'];
    $firstname = $_POST['firstname'];

    try{
        $stmt = $conn->prepare("INSERT INTO clients (phonenumber, firstname) VALUES (:phonenumber, :firstname)");
        $stmt->bindParam(':phonenumber', $phonenumber, PDO::PARAM_STR);
        $stmt->bindParam(':firstname', $firstname, PDO::PARAM_STR);
        $stmt->execute();
    }
    catch (Exception $e) {
        echo "Could not insert data into the database $e";
        echo $e->getMessage();
        exit;
    }

    if($conn->lastInsertId() > 0) {
        echo 'insertion was made';
    }

}
?>

<h2>The Form</h2>
<hr />
<br />
<form action="" method="post">
Number: <input type="text" name="phonenumber" value="" />
<br /><br />
First Name: <input type="text" name="firstname" value="" />
<br /><br />
<input type="submit" name="submit" value="Submit">
</form>
<br />
<hr />

</body>
</html>

旁注:您也可以使用->rowCount()

if($conn->rowCount() > 0) {
    // do your thing
}