PHP使用id和pdo删除记录(初学者)[重复]
Posted
技术标签:
【中文标题】PHP使用id和pdo删除记录(初学者)[重复]【英文标题】:PHP deleting a record using id and pdo (beginner) [duplicate] 【发布时间】:2021-02-10 15:03:44 【问题描述】:我目前正在为我的 mysql 数据库开发一个删除功能。我不擅长编码,发现它非常困难。我需要学习如何制作删除功能,但我已经卡了一段时间了。你可能会嘲笑我的代码,但正如我所说,这对我来说很难。我希望有人能给我提示或帮助我编写代码。
当我像这样运行我的代码时,delete.php 不会发生任何事情
<html>
<head>
</head>
</body>
<table>
<tr>
<th> Naam </th> <th> Soort </th> <th> Prijs </th> <th> Bijzonderheden </th>
</tr>
<?php
$sth = $pdo->prepare('select * from gerechten');
$sth->execute();
while($row = $sth->fetch())
echo "<tr> ";
echo "<td>" . $row['Naam'] . "</td>";
echo "<td>" . $row['Soort'] . "</td>";
echo "<td> " . $row['Prijs'] . "</td>";
echo "<td> " . $row['Bijzonderheden'] . "</td>";
echo "<td> <a href='Delete.php?gerechtID=".$row['ID']."'><button>Delete</button></a> <br> </td>";
echo "</tr> ";
// de update knoppen doorverwijzen met een href --> en dan een form maken voor 1 rij <-----------
?>
</table>
</html>
删除.php
<?php
$id = $_GET['gerechtID'];
$servername = "localhost";
$username = "root";
$password = "";
$naam = $soort = $prijs = $bijzonderheden = "";
$foutmelding1 = $foutmelding2 = $foutmelding3 = $foutmelding4 = "";
try
$pdo = new PDO("mysql:host=$servername;dbname=restaurant", $username, $password);
// set the PDO error mode to exception
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
// connectie is mislukt
catch(PDOException $e)
echo "Connection failed: " . $e->getMessage();
$sth = $pdo->prepare('DELETE FROM gerechten WHERE ID = $id');
?>
【问题讨论】:
【参考方案1】:你错误地使用了准备好的语句,只准备了 DELETE 语句,但没有绑定任何参数并执行它。
https://www.php.net/manual/en/pdo.prepared-statements.php
$sth = $pdo->prepare('DELETE FROM gerechten WHERE ID = ?');
$sth->bindValue(1, $id);
$result = $sth->execute();
【讨论】:
以上是关于PHP使用id和pdo删除记录(初学者)[重复]的主要内容,如果未能解决你的问题,请参考以下文章