我想選擇表格中的最後一個元素。我幸運地做到了,但問題在於,我的循環中的插入總是重複我的第二個表中的條目。我在這裏有我的代碼,我不知道是什麼問題。選擇表格中的最後一個元素
我找到了一種避免檢查是否最後一項還沒有插入但是不起作用的方法。
$p = $pdo->query("SELECT * FROM messagein ORDER BY `Id` DESC limit 1 ");
// SELECT * FROM messagein WHERE Id = (select MAX('Id') from messagein)
echo "<table style='border-width: 1px solid black;'>";
echo "<tr>";
echo "<td> ID </td>";
echo "<td> SendTime </td>";
echo "<td> ReceiveTime </td>";
echo "<td> MessageFrom </td>";
echo "<td> MessageTo </td>";
echo "<td> MessageText </td>";
echo "<td> MessageType </td>";
echo "</tr>";
while ($data = $p->fetch())
{
// $p = $pdo->query("SELECT * FROM messagein ORDER BY `Id` DESC limit 1");
// $data = $p->fetch();
echo "<tr>";
echo "<td>" . $data['Id'] . "</td>";
echo "<td>" . $data['SendTime'] . "</td> ";
echo "<td>" . $data['ReceiveTime'] . "</td> ";
echo "<td>" . $data['MessageFrom'] . "</td> ";
echo "<td>" . $data['MessageTo'] . "</td> ";
echo "<td>" . $data['MessageText'] . "</td> ";
echo "<td>" . $data['MessageType'] . "</td>";
echo "</tr>";
if (substr($data['MessageText'], 0, 3) == "lat")
{
$final = explode(" ", $data['MessageText']);
$latitude = substr($final['0'], 4);
$longitude = substr($final['1'], 5);
$vitesse = substr($final['2'], 6);
$temps = $data['ReceiveTime'];
$exists = $pdo->prepare("SELECT * FROM donneesgps WHERE latitude = ? AND longitude = ? AND temps = ? AND vitesse = ?");
$response = $exists->execute(array(
$latitude,
$longitude,
$temps,
$vitesse
));
echo $response;
if ($response == true)
{
$donneesgps = "INSERT INTO donneesgps (latitude, longitude, temps, vitesse)
VALUES ('$latitude', '$longitude', '$temps', '$vitesse')";
$pdo->exec($donneesgps);
}
}
}
不涉及具體問題,但爲什麼你準備選擇,而不是插入?如果查詢無效(意思是語法上破壞),則execute的結果爲false。 – Jakumi
不確定是什麼問題,請向我們展示樣本數據的當前和預期結果。請閱讀[** How-to-Ask **](http://stackoverflow.com/help/how-to-ask) \t \t這裏是[** START **](http ://spaghettidba.com/2015/04/24/how-to-post-at-sql-question-on-a-public-forum/),瞭解如何提高您的問題質量並獲得更好的答案。 –
我不明白爲什麼你有一個SELECT。 – Strawberry