【问题标题】:Get ID of Last Inserted Record获取最后插入记录的 ID
【发布时间】:2018-11-06 23:57:57
【问题描述】:

我在从名为“订单”的表中最后插入的记录中检索order_id 时遇到问题。

一旦检索到,我希望将其放入我的另一个名为“报告”的表中。

我可以看到这个问题已经被问过很多次了,我也提出了很多建议,但都没有成功。

目前,我的每个表都包含 auto_increment 属性,并且我的函数在“订单”表(不是我想要实现的报告表)上执行成功插入。

function report() {



if(isset($_GET['tx'])) {  

$amount = $_GET['amt']; 
$currency = $_GET['cc'];
$transaction = $_GET['tx']; 
$status = $_GET['st']; 
$total = 0;  
$item_quantity = 0; 




$send_order = query(" INSERT INTO orders (order_amount, order_transaction, order_status, order_currency) VALUES('{$amount}','{$currency}','{$transaction}','{$status}')");


$last_id = last_id(); // this calls last_id in functions.php


confirm($send_order);  




foreach ($_SESSION as $name => $value) { 


if($value > 0 ) { 


if(substr($name, 0, 8) == "product_") { 


$length = strlen($name - 8); 

$id = substr($name, 8 , $length);




$query = query(" SELECT * FROM products WHERE product_id = " . escape_string($id). " " );

confirm($query);



while ($row = fetch_array($query)) {

$product_price = $row['product_price'];
$sub = $row['product_price']*$value;
$item_quantity +=$value;



$insert_report = query(" INSERT INTO reports (product_id, order_id, product_price, product_quantity) VALUES('{$id}','{$last_id}','{$product_price}','{$value}')");
confirm($insert_report); //runs the confirm helper method  




} // end of while loop


$total += $sub; 
echo $item_quantity; 


} // end of substring if statement




}// end of if value




} // end of foreach loop


session_destroy();

} else {


redirect("index.php");


} //end of if isset GET tx




} // end of report function /////////////////

functions.php

function last_id() {

global $connection;

return mysqli_insert_id($connection);



}

【问题讨论】:

  • 警告!您对 SQL 注入完全开放,应该使用准备好的语句而不是像那样构建查询。特别是因为您甚至没有以任何方式转义用户输入。
  • 感谢您的指导......
  • 为什么不在你的函数中接受一个带链接的参数,而不是使用global [...]。所以它会像last_id($link)
  • @Script47 你能告诉我你如何重构它吗
  • 确保 mysqli_insert_id($connection); 插入语句之后进行,以便检索最后一个 id。

标签: php mysqli


【解决方案1】:

您可以在您的 php 页面中插入查询后使用mysqli_insert_id($send_order)

【讨论】:

    【解决方案2】:

    你应该打电话

    $last_id = last_id();
    

    使用后

    confirm($send_order); 
    

    【讨论】:

    • 这有什么帮助?为什么在confirm 之后会起作用?
    【解决方案3】:

    试试这样:

    $send_order = query(" INSERT INTO orders (order_amount, order_transaction, order_status, order_currency) VALUES('{$amount}','{$currency}','{$transaction}','{$status}' )");

    $last_id = $send_order->insert_id;

    【讨论】:

      【解决方案4】:

      您可以使用%d 输出最后一个id。 示例:

      printf("The last id is:  %d", mysqli_insert_id($connection));
      

      【讨论】:

      • 我不想输出它,
      • 你想如何利用最后一个id?
      • 我想根据上面的代码和问题将它从我的“订单”表中取出并自动插入到我的“报告”表中
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-26
      • 2011-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-25
      相关资源
      最近更新 更多