简体   繁体   English

如何使用PHP获取MySQL数据库表中的最后一条记录?

[英]How do I fetch the last record in a MySQL database table using PHP?

I want to fetch the last result in MySQL database table using PHP. 我想用PHP获取MySQL数据库表中的最后一个结果。 How would I go about doing this? 我该怎么做呢?

I have 2 Columns in the Table, MessageID(auto) & Message. 我在表中有2列,MessageID(自动)和消息。

I already know how to connect to the database. 我已经知道如何连接数据库了。

Use mysql_query : 使用mysql_query

<?php
$result = mysql_query('SELECT t.messageid, t.message 
                         FROM TABLE t 
                     ORDER BY t.messageid DESC 
                        LIMIT 1') or die('Invalid query: ' . mysql_error());

//print values to screen
while ($row = mysql_fetch_assoc($result)) {
  echo $row['messageid'];
  echo $row['message'];
}

// Free the resources associated with the result set
// This is done automatically at the end of the script
mysql_free_result($result);

?>

The SQL query: SQL查询:

  SELECT t.messageid, t.message 
    FROM TABLE t 
ORDER BY t.messageid DESC 
   LIMIT 1

...uses the ORDER BY to set the values so the highest value is the first row in the resultset. ...使用ORDER BY设置值,因此最高值是结果集中的第一行。 The LIMIT says that of all those rows, only the first is actually returned in the resultset. LIMIT表示所有这些行中只有第一行实际返回结果集。 Because messageid is auto-increment, the highest value is the most recent one... 因为messageid是自动递增的,所以最高值是最近的值...

Records in a relational database do not have an intrinsic "order" so you cannot fetch the "last" record without some kind of ORDER BY clause. 关系数据库中的记录没有内在的“顺序”,因此如果没有某种ORDER BY子句,则无法获取“最后”记录。

Therefore, in order to fetch the "last" record, simply reverse the ORDER BY clause (change ASC to DESC or vice versa) then select the first result. 因此,为了获取“最后”记录,只需反转ORDER BY子句(将ASC更改为DESC ,反之亦然),然后选择第一个结果。

If you have an auto-increment field and you just want to find the last value that was inserted, you can use the fact that the auto-increment fields are ever-increasing (therefore the "last" one will be the one with the highest value) and do something like this: 如果你有一个自动增量字段,你只想找到插入的最后一个值,你可以使用自动增量字段不断增加的事实(因此“最后一个”将是最高的那个)价值)并做这样的事情:

SELECT *
FROM my_table
ORDER BY id_field DESC
LIMIT 1

Of course you can select the last row by sorting DESC in your query. 当然,您可以通过在查询中排序DESC来选择最后一行。 But what if you want to select the first row and then the last. 但是,如果要选择第一行然后选择最后一行,该怎么办? You can run a new query, but you can also use the function mysql_data_seek . 您可以运行新查询,但也可以使用mysql_data_seek函数。 check code below: 检查以下代码:

$result = mysql_query('YOUR QUERY') or die('Invalid query: ' . mysql_error());
$row_first = mysql_fetch_array($result);
mysql_data_seek($result , (mysql_num_rows($result)-1));
$row_last =  mysql_fetch_array($result);

Hope this helps 希望这可以帮助

The MySql query would look like this: MySql查询看起来像这样:

select MessageID, Message
from Table
order by MessageID desc
limit 1;

I am too rusty with PHP to give you the right syntax for executing this. 我对PHP太生疏了,无法为您提供正确的语法来执行此操作。

This query works because you have an auto-incrementing identifying field ( MessageID ). 此查询有效,因为您有一个自动递增标识字段( MessageID )。 By ordering the results by that field in descending (largest to smallest) order we are effectively returning the records in the table in reverse order. 通过按降序(从最大到最小)顺序按字段排序结果,我们有效地以相反的顺序返回表中的记录。 The limit 1 clause simply limits the result set to one record - the last one in the table. limit 1子句只是将结果集限制为一条记录 - 表中的最后一条记录。

this code of php works fine 这段PHP的代码工作得很好

SELECT t.messageid, t.message 
    FROM TABLE t 
ORDER BY t.messageid DESC 
   LIMIT 1

if you don't have concurrent entries going into some table.b'cause concurrent entries may not go in accordance of their insertion order. 如果你没有并发条目进入某个table.b'因为并发条目可能不符合它们的插入顺序。

for some reason (which I don't know why), my boss force me to get the data in this way: 出于某种原因(我不知道为什么),我的老板强迫我以这种方式获取数据:

$message_arr = array();
while ($row = mysql_fetch_assoc($result)) {
$message_arr['messageid']= $row['messageid'];
$message_arr['message']= $row['message'];

}
return $message_arr;

Of course, you need everything from OMG Ponies's answer I'm just telling you another way to do it =) 当然,你需要OMG小马的答案,我只是告诉你另一种方法=)

I hope this help. 我希望这有帮助。

You should use SELECT query. 您应该使用SELECT查询。 How SELECT works. SELECT如何工作。

SELECT * FROM table - selects everything in a table (id, row 1, row 2,...) SELECT id FROM table - selects only particular row from table. SELECT * FROM table - 选择SELECT * FROM table所有内容(id,第1行,第2行,...) SELECT id FROM table - 仅从SELECT id FROM table选择特定行。

If you now know, how to select, you can use additional logic. 如果您现在知道如何选择,则可以使用其他逻辑。

SELECT * FROM table ORDER by id DESC LIMIT 1;

selects everything from table table, orders it by id - orders it DESCENDING and limits the query to only one result. 从表格中选择所有内容,按ID排序 - 将其命令为DESCENDING并将查询限制为仅一个结果。

If you would do it like this: 如果你这样做:

SELECT * FROM table ORDER by id ASC limit 1; - you would get 1 entry into database. - 你将获得1个数据库入口。

You can order it by any row you want. 您可以按任意行订购。

Hope it helps. 希望能帮助到你。

What do you mean by "the last result"? 你最后的结果是什么意思? You need to precise a bit more. 你需要更精确一点。

Do you mean "the last entry I registered"? 你的意思是“我注册的最后一个条目”?

In this case you should use the appropriate method (depending on the extension you are using) mysqli->insert_id OR mysql_insert_id. 在这种情况下,您应该使用适当的方法(取决于您使用的扩展名)mysqli-> insert_id或mysql_insert_id。

If you mean "the latest entry in the table", an SQL query such as Andrew Hare's is just what you need. 如果您的意思是“表中的最新条目”,那么像Andrew Hare这样的SQL查询就是您所需要的。

Do you mean the last record or do you need the id of the most recently inserted record? 你的意思是最后一条记录还是你需要最近插入记录的id? For that you would use the PHP mysql_insert_id() function. 为此,您将使用PHP mysql_insert_id()函数。 Or if you are using the myusqli extension use $mysqli->insert_id. 或者,如果您使用的是myusqli扩展,请使用$ mysqli-> insert_id。

One thing to remember is that data does not get saved in the insertion order in any MYSQL database. 需要记住的一点是,数据不会以任何MYSQL数据库的插入顺序保存。 So in order to get the last entered record u will have to have an auto increment field. 因此,为了获得最后输入的记录,您必须具有自动增量字段。 Since there is an auto increment field in this table we are good to go. 由于此表中有一个自动增量字段,我们很高兴。

The below script will help to get the last entered record 以下脚本将有助于获取最后输入的记录

<?php    
    $sql = "SELECT * FROM table_name ORDER BY MessageID DESC LIMIT 2";
    $result_set = mysql_query($sql);

    if($result_set){
           while($row = mysql_fetch_array($result_set)) {
               echo "Message Id: ".$row['MessageID']."<br>";
               echo "Message: ".$row['Message']."<br>";
           }
          //creating alert
          echo "<script type=\"text/javascript\">alert('Data was Retrieved 
             successfully');</script>";
     }

     else{
         //creating alert
         echo "<script type=\"text/javascript\">alert('ERROR! Could Not Retrieve 
             Data');</script>";
     }
?>

The query selects all the records in the table and orders them according to the descending order of the MessageID (as it is the auto increment field) and limits the returned result to only one record. 查询选择表中的所有记录,并根据MessageID的降序(因为它是自动增量字段)对它们进行排序,并将返回的结果限制为仅一个记录。 So since the table is ordered according to the descending order of the MessageID only the last entered record will be returned. 因此,由于表是按照MessageID的降序排序的,所以只返回最后输入的记录。

NOTE: if you are using a newer version you will have to use mysqli_query($connection_variable,$sql); 注意:如果您使用的是较新版本,则必须使用mysqli_query($ connection_variable,$ sql); instead of mysql_query($sql); 而不是mysql_query($ sql); and
mysqli_fetch_array($result_set) instead of mysql_fetch_array($result_set) mysqli_fetch_array($ result_set)而不是mysql_fetch_array($ result_set)

$result = mysql_query('select max(id) from your_table  ') or die('Invalid query: ' . mysql_error());
  while ($row = mysql_fetch_assoc($result)) {
  echo $row['id'];
  echo $row['message'];
}

// 
// 
mysql_free_result($result);

simple like that 很简单

$statement = $PDO->prepare("
SELECT MessageID,
Message
FROM myTable
ORDER BY MessageID DESC
LIMIT 1;
");
$statement->execute();
$result = $statement->fetch(\PDO::FETCH_ASSOC);

echo $result['MessageID']." and ".$result['Message'];

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

相关问题 如何使用PHP和MySQL数据库获取上次登录日期时间? - How to fetch last login datetime using PHP and MySQL database? 如何使用PDO删除插入MySQL表的最后一条记录? - How do I delete the last record inserted into a MySQL table using PDO? 如何使用PDO查找数据库表的最后一条记录? - How do I find the last record my database table using PDO? 如何在 PHP 中获取 MySQL 表的最后插入 ID? - How do I get the last inserted ID of a MySQL table in PHP? 如何使用最后插入的id从mysql获取记录? - How to fetch record from mysql using last inserted id? 如何在mysql中使用JOIN Query提取不同的值以及最后一条记录? - How can I fetch Distinct Value as well as last record using JOIN Query in mysql? 使用php和mysql从两个不同的表中获取记录? - Fetch record from two different table using php and mysql? 如何从MySQL中获取多行,并使它们成为复选框的值,以将其插入php中数据库的另一个表中? - How Do I fetch multiple rows from MySQL and and make them the value of checkbox(es) to be inserted to a another table in the database, in php? 如何使用PHP和MySQL按日期从表中获取最近7天的记录 - How to get last 7 days record from table as per date using PHP and MySQL 如何使用PHP和CURL将记录添加到表中? - How do I add a record to a table using PHP and CURL?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM