使用pdo和oop链接删除行php

时间:2018-05-10 07:30:11

标签: php sql oop pdo

我的情况:在用户登录后......它会在表格中显示他所拥有的书...我在每本书的旁边添加了删除链接...例如我点击链接删除我想要的一边数学书删除它..我怎么能这样做。 我得到了书籍但是当我点击删除链接时没有任何事情发生。

此功能在用户登录时显示书籍

public function getBooks($start = 0, $limit = 2)
{
    $sql_start = $start * $limit;
    $sql_limit = $limit;

    //SELECT loginUser.username, Library.nameOfBook FROM loginUser JOIN userBook JOIN Library ON userBook.user_id = loginUser.id AND userBook.book_id = Library.id WHERE loginUser.username="loay";
    $query = "SELECT Library.nameOfBook FROM loginUser JOIN userBook JOIN Library ON userBook.user_id = loginUser.id AND userBook.book_id = Library.id WHERE loginUser.username=:username LIMIT $sql_start, $sql_limit";
    $statment = $this->db->prepare($query);
    $statment->execute([
        ':username' => $this->username
        //,':start' => $start, ':limit' => $limit
    ]);
    $result = $statment->fetchAll();

   echo "<table border='1'>
    <tr>
    <th>Books</th>
    <th>Action</th>
    </tr>";
    foreach($result as $row){
        echo "<tr>";
        echo "<td>" . $row['nameOfBook'] . "</td>";
        echo "<td>" ."<input type='submit' name='delete' value='Delete' method='post' " . "</td>";
        echo "</tr>";
    }
    echo "</table>";

    if(isset($_POST['delete'])){

        deleteBooks($id1, $id2);
    }
}

这个函数deleteBooks

  public function deleteBooks($id1, $id2)

{

    $id1 = $_GET['user_id'];
    $id2 = $_GET['book_id'];
    $query = "Delete FROM  userBook WHERE userBook.user_id=id1 AND userBook.book_id =id2";
    $statment = $this->db->prepare($query);
    $statment->execute([$id1, $id2]);
    $result = $statment->rowCount();
    $this->deleteBooks= ($result == "1");
    return $this->deleteBooks;

}

1 个答案:

答案 0 :(得分:-1)

首先,你必须在链接上添加book.id

echo "<a href='?deleteBooks&id={$row['id']}' onClick=\"return confirm('Are you sure you want to delete?')\">Delete</a>";

点击“是”后,您将收到一条获取请求。 不确定删除函数的调用位置,但您可以传递$ _GET 参数deleteBooks($_GET['id])。 和它自己的功能 public function deleteBooks($book_id) { $query = "Delete FROM userBook WHERE userBook.user_id=? AND userBook.book_id =?"; $statment = $this->db->prepare($query); $statment->bind_param("ss", $user_id, $book_id); $statment->execute(); // } 您应该在会话中存储user_id。