由于未知原因无法访问变量

时间:2015-07-02 16:13:24

标签: php mysql

我试图执行两个INSERT语句,我需要最后插入的id来执行此操作。我试过了$question_id = $dbh->lastInsertId();,但它没有用。现在我正在执行额外的SELECT LAST_INSERT_ID()声明,但这也不起作用。我一直收到此错误:SQLSTATE[HY093]: Invalid parameter number: parameter was not defined,这是因为$question_id为空,因为选择最后一个插入ID似乎无效。

这是我的代码:

public function add_question($user_id, $group_id, $title, $caption, $datetime, $status) {        
    // Add user to database
    try {
        $dbh = new DBHandler();

        $sql = 
        "INSERT INTO question(
                user_id,
                group_id,
                title,
                caption,
                created_date_time,
                question_status
            ) 
            VALUES(
                :user_id,
                :group_id,
                :title,
                :caption,
                :created_date_time,
                :question_status
            )";

        $stmt = $dbh->get_instance()->prepare($sql);

        $stmt->execute(
            array(
                ':user_id' => $user_id,
                ':group_id' => $group_id, 
                ':title' => $title, 
                ':caption' => $caption, 
                ':created_date_time' => $datetime,
                ':status' => $status
             )
        );

        //$question_id = $dbh->lastInsertId();

        $sql= "SELECT LAST_INSERT_ID() AS question_id"; 
        $stmt = $dbh->get_instance()->prepare($sql);
        $stmt->execute();

        // Resultset
        $result = $stmt->fetchAll();

        foreach($result AS $question_id_row) {
            $question_id = $question_id_row['question_id'];
        }

        $sql = 
        "INSERT INTO notification(
            n_question_id,
            n_question_user_id,
            n_question_group_id,
            n_question_title
        ) 
        VALUES(
            :n_question_id,
            :n_question_user_id,
            :n_question_group_id,
            :n_question_title
        )";

        $stmt = $dbh->get_instance()->prepare($sql);

        $stmt->execute(
            array(
                ':n_question_id' => $question_id, 
                ':n_question_user_id' => $user_id, 
                ':n_question_group_id' => $group_id,
                ':n_question_title' => $title
             )
        );

        echo 'Question added!';
    } 
    catch(PDOException $e) {
        echo $e->getMessage();
    }   
}

1 个答案:

答案 0 :(得分:1)

您的查询因“{1}}和invalid number of parameter而失败,因为您定义了此参数

parameter was not defined

但你绑定

:question_status

变化

':status' => $status

它会起作用