獲取 php 和 mysqli 中插入數據的 ID (Get Id of inserted data in php and mysqli)


問題描述

獲取 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";      
}

這就是表格的樣子。enter image description here

如何獲取插入數據的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 HolmespravaUmesh ChauhanOldSteve)

參考文件

  1. Get Id of inserted data in php and mysqli (CC BY‑SA 2.5/3.0/4.0)

#mysqli #MySQL #PHP






相關問題

如何第一次創建 mysqli 數據庫? (how can I creates a mysqli database for first the first time?)

使用 jquery autosuggest 從多個表中選擇 (select from multiple tables with jquery autosuggest)

無法連接 - 數據庫或編碼錯誤 (Could Not Connect - Database or Coding Error)

mysqli忽略表中的第一行 (mysqli ignoring the first row in a table)

從數據庫導入的鏈接以 UTF8 截斷 (imported link from database cut off at UTF8)

試圖獲取非對象的屬性 (Trying to get property of non-object)

獲取 php 和 mysqli 中插入數據的 ID (Get Id of inserted data in php and mysqli)

WAMP 和 mysqli::real_connect(): (HY000/2002)? (WAMP and mysqli::real_connect(): (HY000/2002)?)

如何將 MySQLi 準備好的語句的結果放入關聯數組中? (How can I put the results of a MySQLi prepared statement into an associative array?)

測試選擇查詢是否找到結果 (Testing if a Select Query found results)

為什麼我的正確連接嘗試在 apache2 下失敗但在 cli 下失敗? (Why is my correct connection attempt failing under apache2 but not under cli?)

在帶有數組的 IN 語句之後,在 WHERE 語句中使用更多佔位符 (Use more placeholders in WHERE statement after IN statement with arrays)







留言討論