我想显示数据库中的最后一条记录(行)

时间:2012-09-03 06:49:04

标签: php mysql sql database

但我不知道如何以及在哪里将sql代码放在php中,有人可以帮帮我吗?我知道它类似于SELECT * FROM form ORDER BY 'Klant_id' ASC LIMIT 1

<html>
    <header>
    <link rel="stylesheet" href="css/style.css" type="text/css"  />
    </header>
    <body>

     <?php 
             //makes an connection to the db

             mysql_connect("localhost", "root", '') or die(mysql_error());
             mysql_select_db('databaseimage') or die(mysql_error());

             $data = mysql_query("SELECT * FROM form ORDER BY 'Klant_id' ASC LIMIT 1")
             or die(mysql_error()); 

             echo "<table border cellpadding=3>"; 
             while($info = mysql_fetch_array( $data)) 
             { 
             echo "<tr>";    
             echo "<th>surname:</th> <td>".$info['Surname'] . "</td> "; 
             echo "<th>insertion:</th> <td>".$info['Insertion'] . "</td> ";
             echo "<th>initials:</th> <td>".$info['Initials'] . "</td> ";
             echo "<th>name:</th> <td>".$info['Name'] . "</td> "; 
             echo "<th>sex:</th> <td>".$info['Sex'] . "</td> ";
             echo "<th>adress:</th> <td>".$info['Adress'] . "</td> ";
             echo "<th>postcode:</th> <td>".$info['Postcode'] . "</td> ";
             echo "<th>location:</th> <td>".$info['Location'] . "</td> ";
             echo "<th>private phone:</th> <td>".$info['Private_phone'] . "</td> ";
             echo "<th>mobile phone:</th> <td>".$info['Mobile_phone'] . "</td> ";
             echo "<th>work phone:</th> <td>".$info['Work_phone'] . "</td> ";
             echo "<th>private email:</th> <td>".$info['Private_email'] . "</td> ";
             echo "<th>work email:</th> <td>".$info['Work_email'] . "</td> ";

             } 
             Print "</table>"; 
             ?> 
    </body>
    </html>

3 个答案:

答案 0 :(得分:2)

不要用单引号包裹列Klant_ID。单引号与反引号非常不同。

SELECT * 
FROM form tablename 
ORDER BY Klant_id DESC 
LIMIT 1

SELECT * 
FROM form tablename 
ORDER BY `Klant_id` DESC 
LIMIT 1

<强>差异:

Backticks(`)将用于表和列标识符,但仅在标识符为 MySQL reserved keyword 时才需要。

Single quotes(')应该用于VALUES()列表中的字符串值。

MySQL也支持

Double quotes的字符串值,但单引号被其他RDBMS更广泛地接受,因此使用单引号而不是双引号是一个好习惯。

答案 1 :(得分:1)

当你有auto_increment的主键时,你应该使用DESC降序来获取它。为了获取最后插入的记录。

试试这个。

SELECT * FROM form ORDER BY `Klant_id` DESC LIMIT 1

答案 2 :(得分:0)

如果你有设置了auto_increment的主键。你可以用两种方式做到这一点

<强>第一

SELECT * FROM form WHERE Klant_id=(select MAX(Klant_id) FROM form)

<强>第二

SELECT * FROM form ORDER BY Klant_id DESC LIMIT 1;