問題描述
獲取 php 和 mysqli 中插入數據的 ID (Get Id of inserted data in php and mysqli)
我正在從另一個頁面收集數據並將其發送到處理並將數據發送到我的數據庫表。這是代碼。
require "config.php";
if ( $_POST['insertPost'] == true ){
$postTitle = $_POST['title'];
$postContent = $_POST['content'];
$postImage = $_POST['image'];
$postDate = $_POST['datetime'];
$categories = $_POST['categories'];
$c‑>query( "INSERT INTO blog ( title, content, image, datetime, categories ) VALUES ( '$postTitle', '$postContent', '$postImage','$postDate', '$categories')" );
//echo "Inserted";
}
如何獲取插入數據的ID信息並將其存儲到變量?
參考解法
方法 1:
Use mysqli to do DB operation as mysql is deprecated now. So, try this:
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con, "INSERT INTO blog (title, content, image, datetime, categories) VALUES ('$postTitle', '$postContent', '$postImage','$postDate', '$categories')");
// store auto‑generated id
$lastInsertedId = mysqli_insert_id($con);
mysqli_close($con);
方法 2:
The MySQL function LAST_INSERT_ID()
does just what you need: it retrieves the id that was inserted.
The PHP function mysql_insert_id()
does the same as calling SELECT LAST_INSERT_ID() with mysql_query().
方法 3:
Currently I have insufficient reputation to add a comment so can only post an answer. Within my database I have a similar requirement and use:‑
sql = "Select Max(idResults) from Results"
idResults being AI (auto increment)
(by Ryan Holmes、prava、Umesh Chauhan、OldSteve)