这绝对是初学者的问题。有两个问题。即使我从表中删除行(我使用的是phpmyadmin),我的MYSQL表中的id(设置为autoincrement)也会继续上升。至于另一个问题,我似乎无法找到一种方法来处理用户最近输入的行。代码回显了MYSQL中的所有现有行。 我加粗了最相关的代码部分。
<?php
//establish connection to mysql
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
/*retrieve user input from input form
and initialize variables */
$Word1 = $_POST["Word1"];
$Word2 = $_POST["Word2"];
$Word3 = $_POST["Word3"];
$Word4 = $_POST["Word4"];
$Word5 = $_POST["Word5"];
//select db
mysql_select_db("madlibs", $con);
//insert user input for word 1
$sql = "INSERT INTO test (Word1, Word2, Word3, Word4, Word5)
VALUES
('$Word1', '$Word2', '$Word3', '$Word4', '$Word5')";
if(!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
$result = mysql_query ("SELECT * FROM test");
/* take note here */
while($row = mysql_fetch_array($result))
{
echo $row['Word1'] . " " . $row['Word2'] . " " . $row['Word3'] . " " .
$row['Word4'] . " " . $row['Word5'] . " " . $row['id'];
echo "<br />";
} /* take note here */
mysql_close($con);
?>
答案 0 :(得分:2)
$result = mysql_query ("SELECT * FROM test order by id desc limit 1");
关于你的id问题......这就是id的工作原理。他们没有填补空白。
旁注:永远不要将用户提交的数据直接放入查询字符串中。总是使用mysql_real_escape_string()来逃避它们。
答案 1 :(得分:0)
SELECT * FROM test ORDER BY Id DESC LIMIT 1