用PHP删除mySql行

时间:2015-09-13 18:11:39

标签: php mysql row sql-delete

我有商店网站,希望能够删除我添加的内容,但似乎无法让它发挥作用。

所有相关代码如下:

主页:

<?php
  //external pages area
  include_once('config/database.php');
  include_once('object/chair.php');
  //grabs info from the various pages.sql files
  $database = new Database();
  $conn = $database->getConnection();
  $chair = new Chair($conn);
  //connection made with sql file
  $stmt = $chair->readAll();
  //reading all the data in the sql file
  while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
?>
    <div class="ProductActionAdd" style="display:;">
      <a href="chair-details.php?detailsid=<?php echo $row['ID'];?>" class="btn">Buy me!</a>
    </div>

详细信息页面:

<?php
  include_once('config/database.php');
  include_once('object/chair.php');
  $database = new Database();
  $conn = $database->getConnection();
  $chair = new Chair($conn);
  $chair->id = $_GET['detailsid'];
  $stmt = $chair->readDetails();
  while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
?>
    <a href='delete-chair.php?detailsid=<?php echo $row['ID'];?>' class="deleteit">deleate</a>

删除页面:

<?php
  include_once('config/database.php');
  include_once('object/chair.php');
  $database = new Database();
  $conn = $database->getConnection();
  $chair = new Chair($conn);
  $chair->id = $_GET['detailsid'];
  $stmt = $chair->readAll();
  while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
?>
    <div class="center_items">
      <div class="all-items">
        <?php   
          $sql="DELETE FROM office_chairs WHERE id ='{$chair->id}'";    
  }
        ?>

它声明detailsID未定义且类主席的对象无法转换为字符串。

2 个答案:

答案 0 :(得分:1)

嗯......您通过detailsid收到$_GET参数,然后将其指定给名为id的媒体资源。

$chair->id = $_GET['detailsid'];

因此,调用名为$ detailsid的变量是不可能的 - 因为不存在这样的变量。请改为使用您指定值的属性。

$ chair变量包含类Chair的新实例。我不知道你的意图是什么?数据库表名是否动态?如果没有,只需写表名。

更正您的查询
$sql="DELETE FROM $chair WHERE id = '$chair->id'";

为:

$sql="DELETE FROM table_name_here WHERE id ='$detailsid'";

可能会解决您想要的结果问题。但是您的代码很容易受到SQL注入的攻击。您应该考虑使用准备好的语句,而不是直接将变量连接到查询。

例如

$sql="DELETE FROM table_name_here WHERE id = ?";
$stmt -> $con = prepare($sql);
$stmt -> execute(array($chair -> id));

答案 1 :(得分:1)

更新

$sql="DELETE FROM $chair WHERE id ='$detailsid'";

$sql="DELETE FROM chair WHERE id ='{$chair->id}'";