通过PHP删除数据库行

时间:2015-07-04 17:13:57

标签: php mysql pdo

我已经查看了"建议"根据标题我把它放在那里,主题要么没有回答,要么与我的情况没有关系(从我能看到的)。

我有一个PHP HTML页面,它调用数据库中的信息并将其输入到表中。我已经准备好了删除功能的标签,但我似乎无法做到正确。我希望有人可以帮助我。

这些都是相关页面。

connection.php

<?php
    try{
        $handler = new PDO('mysql:host=127.0.0.1;dbname=data', 'root', 'root');
        $handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }catch(PDOException $e){
        echo 'ERROR: ' . $e->getMessage();
    }
?>

location1.php

<?php
include('connection.php');
$query = $handler->query('SELECT * FROM subsordered WHERE location ="location1"');
$delete = $handler->query('DELETE * FROM subsordered WHERE id = :id');

?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
    <h1 align="center">Location 1</h1>
    <table align="center" border="1" height="10%" width="80%">
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Desc</th>
            <th>Location</th>
            <th></th>
    </tr>
    <?php while($row = $query->fetch()){ '<tr>
        <td align="center">';echo $row[''],'</td>
        <td align="center">';echo $row['id'],'</td>
        <td align="center">';echo $row['name'],'</td>
        <td align="center">';echo $row['desc'],'</td>
        <td align="center">';echo $row['location'],'</td>
        <td align="center"><a href="connection.php?id='.$row['id'].'">Delete</a></td>
    </tr>';}  ?>
</table>

当我尝试在location1的第一个php部分中保留mysql删除调用时会打破页面,我很确定它与我为1个函数分配2个调用这一事实有关但我除了为一个删除电话创建一个全新的页面jsut我不知道还能做什么

2 个答案:

答案 0 :(得分:2)

尝试:

<?php
include('connection.php');
$query = $handler->query('SELECT * FROM subsordered WHERE location ="location1"');
if (isset($_GET["id"])) {
  $delete = $handler->exec('DELETE FROM subsordered WHERE id = \'' . $_GET["id"] . '\'');
}

?>

这应该有效。无论如何,我会考虑更改代码以防止SQL注入(检查this

答案 1 :(得分:0)

我对PDO并不熟悉,但从我看到的这一行有问题:

$delete = $handler->query('DELETE * FROM subsordered WHERE id = :id');

我认为应该这样:

$delete = $handler->query('DELETE FROM subsordered WHERE id = :id');

请查看此处的示例:http://www.mustbebuilt.co.uk/php/insert-update-and-delete-with-pdo/