准备好的声明没有执行

时间:2014-11-11 14:12:36

标签: php mysql mysqli prepared-statement

我在PHP中有后端的简单Web应用程序。我试了三个小时,但无法解决问题。

我的代码如下:

1。 db_connect.php

<?php

define("HOST", '127.0.0.1');
define("USER", 'root');
define("PASSWORD", '');
define("DB", 'tourist guide');


$con = new mysqli(HOST,USER,PASSWORD,DB);

if ($con->connect_errno){
    die("Database Connection Failed");
    exit();    
}

2。的index.php

<?php

require_once 'db_connect.php';

$response = array();       
$result = "";


if (isset($_POST['firstname']) && isset($_POST['lastname']) && isset($_POST['email'])&& isset($_POST['password'])) {

    $firstname = $_POST['firstname'];       
    $lastname = $_POST['lastname'];     
    $email = $_POST['email'];       
    $password = $_POST['password'];    

    $stmt = $con->prepare("INSERT INTO 
                                      user_accounts
                                      (first_name,last_name,email,password)
                                VALUES
                                      (?,?,?,?)");

    echo 'prepared statement executed. ';

    $stmt->bind_param('ssss', $firstname, $lastname, $email, $password); 

    echo 'values given. ';

    $result = $stmt->execute();

    echo 'statement is executed. ';

    $stmt->close();

}

if ($result) {

    $response["success"] = 1;
    $response["message"] = "account successfully created.";
    echo json_encode($response);

} else {

    $response["success"] = 0;
    $response["message"] = "An error occurred during registration.";
    echo json_encode($response);
}

&GT;

输出如下:

prepared statement executed. values given. statement is executed. {"success":0,"message":"An error occurred during registration."}

只有错误必须是$result = $stmt->execute();。我错了吗?或者错误是别的什么?请帮助。

更新:

根据弗雷德的评论,我补充道:

if(!$stmt->execute()){trigger_error("there was an error....".$con->error, E_USER_WARNING);} 

现在他出现了真正的错误:

Cannot add or update a child row: a foreign key constraint fails

看起来错误在我的数据库外键中......我稍后会解决它。如果你现在知道错误,那么请说出来...谢谢弗雷德。

1 个答案:

答案 0 :(得分:3)

根据OP希望结束问题,看到错误已经找到。

您好像过早关闭了数据库连接。

在结束$stmt->close();代码前放置?>

此外,代替包含if/else的整个$result = $stmt->execute();块,将其替换为if(!$stmt->execute()){trigger_error("There was an error....".$con->error, E_USER_WARNING);},以便查看真正的错误导致其失败。

您还应将die("Database Connection Failed");替换为
die('Connection failed [' . $con->connect_error . ']');
在你的连接失败的情况下获得真正的错误。

看到问题出在您的外键上。