简体   繁体   English

选择最后一个 id,不插入 PDO

[英]select last id, without insert in PDO

Tried this but i still cant make it work.试过了,但我仍然无法让它工作。

Edited:编辑:

I want to get the id's for each of my Fruits without insert in PDO.我想在不insert PDO 的情况下获取每个Fruits 的id's

//apple
//orange

foreach($_POST['fruits'] as $fruits) {

     $a = recordFruit($fruits); 

      if(!empty($a)) {
         $id = id_of_this_fruit(); //get ID of apple, then orange. so on..
         echo $id[0]."<br />";
      }
}


function id_of_this_fruit(){
    ...
    $query = "SELECT * FROM fruits ORDER BY id DESC LIMIT 1;
    ...
    $row = $sql->fetchALL();
    return $row;
}

Edited: after some changes in the query.编辑:在查询中进行一些更改后。 my code returns value.我的代码返回值。 but its not returning the recently added data.但它没有返回最近添加的数据。 it shows the old ID prior to the insertion of new fruits.它在插入新水果之前显示旧 ID。

You can get last id by querying with order by and limit if ID is auto increment.如果 ID 是自动递增,您可以通过 order by 和 limit 查询来获取最后一个 id。

SELECT * 
FROM fruits 
ORDER BY ID DESC
LIMIT 1

This will only work if you are using a table.这仅在您使用表格时才有效。 If you are using the alias with multiple tables in the WHERE clause, will fail SQL Error (1221): Incorrect usage of UPDATE and ORDER BY如果在WHERE子句中使用具有多个表的别名,将失败 SQL Error (1221): Incorrect usage of UPDATE and ORDER BY

SELECT * FROM fruits  ORDER BY id DESC LIMIT 1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM