我正在测试使用mysqli_insert_id获取最后auto_increment_ID的功能。当我发现如果我使用两种不同的方法,结果是不同的,我感到很困惑。
方法1<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT into item(uid,item_id,item_name,item_price,item_quantity)
VALUES('1','0','hhh','23','23');";
if (mysqli_query($conn, $sql)) {
$last_id = mysqli_insert_id($conn);
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
这个程序的方式是工作的,因为我可以得到最后一个ID。
方法2
db.php
class db{
protected $db_host;
protected $db_name;
protected $db_user_name;
protected $db_pass;
public function __construct($host,$db_n,$user_n,$pass) {
$this->db_host=$host;
$this->db_name=$db_n;
$this->db_user_name=$user_n;
$this->db_pass=$pass;
}
public function conn(){
return mysqli_connect($this->db_host, $this->db_user_name, $this->db_pass, $this->db_name);
}
}
test.php
require "db.php";
$db=new db('localhost','bs','root','');
$sql = "INSERT into item(uid,item_id,item_name,item_price,item_quantity)
VALUES('1','0','hhh','23','23');";
if (mysqli_query($db->conn(), $sql)) {
$last_id = mysqli_insert_id($db->conn());
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($db->conn());
}
mysqli_close($db->conn());
这个方法根本不起作用…它会得到结果0。有人知道我哪里出错了吗?
只初始化->conn()
方法一次,然后重用它。每次调用都会创建一个新的:
$db = new db('localhost','bs','root','');
$connection = $db->conn(); // initialize once
$sql = "INSERT into item(uid,item_id,item_name,item_price,item_quantity)
VALUES('1','0','hhh','23','23');";
if (mysqli_query($connection, $sql)) {
$last_id = mysqli_insert_id($connection);
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $sql . "<br>" . $connection->error;
}
$connection->close();
或者使用面向对象接口(->insert_id
属性):
$db = new db('localhost','bs','root','');
$connection = $db->conn(); // initialize once
$sql = "INSERT into item(uid,item_id,item_name,item_price,item_quantity)
VALUES('1','0','hhh','23','23');";
if($connection->query($sql)) {
$last_id = $connection->insert_id;
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $sql . "<br>" . $connection->error;
}
$connection->close();
仅仅因为调用了$db->conn()两次,所以需要将$db->conn()赋值给一个变量。如下:
require "db.php";
$db=new db('localhost','bs','root','');
$sql = "INSERT into item(uid,item_id,item_name,item_price,item_quantity)
VALUES('1','0','hhh','23','23');";
$conn = $db->conn();
if (mysqli_query($conn, $sql)) {
$last_id = mysqli_insert_id($conn);
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);