我正在使用mysqli_insert_id测试获取最后一次auto_increment_ID的功能。当我发现如果我使用2种不同的方法时,我感到很困惑,结果是不同的。
方法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。谁知道我哪里出错了?
答案 0 :(得分:1)
只是因为你两次调用$ db-&gt; conn(),你需要将$ db-&gt; 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);
答案 1 :(得分:1)
只初始化->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();