通过程序获取最后一个记录ID

时间:2012-07-31 05:16:10

标签: php mysqli mysql-insert-id

我是新学员,并尝试获取记录的最后插入ID。

但是在这里它给了我以下错误:

错误:您的SQL语法出错;检查与MySQL服务器版本对应的手册,以便在第1行的“SELECT @p_customerId”附近使用正确的语法

任何想法如何解决这个问题。

谢谢,

<?php
class MyConnection{ 
    var $db_host = '127.0.0.1';
    var $db_user = 'root';
    var $db_password = 'xxx';
    var $db_name = 'xxx';
    var $connection;

    function Connect(){
        $this->connection = @mysqli_connect($this->db_host, $this->db_user, $this->db_password) 
        or 
        die("Error: ".mysqli_connect_error());
        mysqli_select_db($this->connection, $this->db_name);
        mysqli_query($this->connection, "SET NAMES 'utf8'");
    }

    function Disconnect(){
        mysqli_close($this->connection);
    }

    function ExecSQL($query){
        $result = mysqli_query($this->connection, $query) or die('Error: '.mysqli_error($this->connection));
        return $result;
    }

    function LastInsertId() {
        return mysqli_insert_id();
    }
}

if (isset($_POST['btnSubmit'])) {
    $v_custname = mysql_real_escape_string($_POST['txtcustname']);
    $v_custphone = mysql_real_escape_string($_POST['txtcustphone']);
    $v_custemail = mysql_real_escape_string($_POST['txtcustemail']);

    $conn = new MyConnection();
    $conn->Connect();
    $conn->ExecSQL("CALL sp_customer('$v_custname','$v_custphone','$v_custemail',@p_customerId); SELECT @p_customerId;");
    echo $conn->LastInsertId();
    $conn->Disconnect();

}
?>

这是程序;

CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_customer`(IN `p_customerName` VARCHAR(50), IN `p_customerPhone` VARCHAR(50), IN `p_customerEmail` VARCHAR(50), OUT `p_customerId` INT)
    LANGUAGE SQL
    NOT DETERMINISTIC
    CONTAINS SQL
    SQL SECURITY DEFINER
    COMMENT ''
BEGIN
INSERT INTO customer(CustomerName, CustomerPhone, CustomerEmail)VALUES(p_customerName, p_customerPhone, p_customerEmail);
SELECT LAST_INSERT_ID() as p_customerId;
END

1 个答案:

答案 0 :(得分:1)

您尝试在一个查询中执行多个语句。

阅读本文:http://php.net/manual/en/mysqli.quickstart.multiple-statement.php

当然,我不知道为什么你在查询中添加了SELECT @p_customerId; ...你的下一行代码无论如何都会请求最后一个插入ID。你为什么不把它拿出来做一个单语句查询?