我想要删除数据库中的一行,所以当我单击该按钮时,它会删除该行。我环顾四周并找到了示例,但这些内容与外部PHP表有关,但我希望将我的内容包含在同一张表中。我的代码是:
if(isset($_GET['deleteId']))
{
$query = mysql_query("DELETE FROM kingswinfordcc_vehicles WHERE vehicleid = '$_GET['deleteId']'");
header("Location: vehicle-table.php");
}
如果我正确的话会删除指定表中的行,然后将用户移动到新页面。
然后我的表格中有一个我目前用作链接的按钮,如下所示,所以当点击链接回到同一页面时
<td> <a href="vehicle-table.php?deleteId=<?php echo $vehicle_row['vehicleid'] ?>">Delete</a></td>
我只是这样做,正如一位资深同事告诉我的那样。非常感谢任何建议/帮助。
答案 0 :(得分:1)
您可以执行以下操作,将表单操作引导至与您要点击的按钮相同的页面
if(!isset($_GET['deleteId'])
{
$mysqli = new mysqli("host", "user", "pass", "table");
$sql = "DELETE FROM kingswinfordcc_vehicles
WHERE vehicleid = ?"
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('i', $_GET['deleteId']);
$stmt->execute();
$stmt->close();
$mysqli->close();
}
我强烈建议您在某些验证中添加他们希望永久删除该项目的内容,您甚至可以添加try/catch语句
答案 1 :(得分:0)
您的查询包含多个相同类型的引号。我认为以下内容可行:
if(isset($_GET['deleteId']))
{
$query = mysql_query('DELETE FROM kingswinfordcc_vehicles WHERE vehicleid = ' . mysql_real_escape_string($_GET['deleteId']));
header("Location: vehicle-table.php");
}
答案 2 :(得分:0)
这是学术性的,所以我会用mysql_ *函数给你非常简单的答案
$id = intval($_GET['deleteId'], 0); //this function parses the param to int if it is not number there will be 0
if($id) //checking if id is true(not zero)
{
$query = mysql_query("DELETE FROM `kingswinfordcc_vehicles` WHERE `vehicleid` = '$id'");
header("Location: vehicle-table.php"); //after query moving to vehicle-table.php if query fail and show msg it this line won't move user to this page!
}
请记住,您需要使用mysql连接来执行此类查询。
PDO解决方案:
<?php
/* Connect to an ODBC database using driver invocation */
$dsn = 'mysql:dbname=testdb;host=127.0.0.1'; //fill with proper data
$user = 'dbuser';
$password = 'dbpass';
$id = (int)$_GET['id'];
try{
$dbh = new PDO($dsn, $user, $password);
$st = $a->prepare("UPDATE `users` SET user=:id");
$st->bindParam(":id", $id, PDO::PARAM_INT);
$st->execute();
header("Location: vehicle-table.php");
//echo $st->rowCount(); //this line will show how many rows were deleted
}
catch (PDOException $e){
echo 'Error: ' . $e->getMessage();
}
?>