【问题标题】:Deleting a Post/Entry by User in PHP在 PHP 中按用户删除帖子/条目
【发布时间】:2017-09-19 02:38:57
【问题描述】:

我正在设计一个简单的图书应用程序。我有用户登录、出售或购买书籍,他们也有一些帐户设置,包括管理帖子,用户可以在其中删除他们添加到系统中的书籍。

我需要有关如何执行此操作的帮助。当用户按下“管理帖子”按钮时,我想要一个用户可以在其中键入 Book_ID 的输入字段和一个“删除”按钮,他们可以在其中单击它以将图书从系统中删除。

现在,当您添加一本书时,我无法将其设置为将其链接到登录的特定用户(不知道该怎么做),因此用户将能够删除任何书。我在这个项目上没时间了,所以我现在不用担心了。我只需要用户能够通过表上的字段查看数据库中的所有书籍:Book_ID、ISBN、Title、Author - 然后用户将 Book_ID 输入到输入字段中,单击“删除”按钮和book 被用户从数据库中删除。

数据库名称:nextbook 表:书籍 字段:book_ID、ISBN、作者、标题(希望查看这些)

以下是我从另一个页面获得的代码模板,我认为它会类似。除了,我需要将删除 SQL 放在某处:

<?php


if(isset($_POST['search']))
{
    $valueToSearch = $_POST['valueToSearch'];

    $query = "SELECT * FROM books";

    $search_result = filterTable($query);

}
else {
    $query = "SELECT * FROM books";
    $search_result = filterTable($query);
}

// function to connect and execute the query
function filterTable($query)
{
    $connect = mysqli_connect("localhost", "Admin", "Password", "nextbook");
    $filter_Result = mysqli_query($connect, $query);
    return $filter_Result;
}

?>

<!--Html -->

<!DOCTYPE html>
<html lang="en">
<head>

    <meta charset="UTF-8" >

    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <script src="http://ie7-js.googlecode.com/svn/version2.1(beta4)/IE9.js"></script>


    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">


    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
    <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
    <script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>


    <style>
        table {
            border-collapse: collapse;
            width: 30%;
        }

        th, td {
            text-align: left;
            padding: 5px;
        }

        tr:nth-child(even){background-color: #f2f2f2}

        th {
            background-color: #007d5f;
            color: white;
        }
    </style>
    <link rel="stylesheet" href="NextBook1.css"/>


    </head>
    <body>

    <div data-role="page" id="Manage_Posts">
    <div data-role="header" data-theme="b">
        <h1>NextBook</h1>
        <a href="Login.php" data-icon="power" class="ui-btn-right" data-theme="a" data-mini="true">Sign Out</a>
    </div>


    <br>

    <div class="logo" align="center">
        <img src="Images/image1%20-%20Copy.PNG" width="100" height="100" ">
    </div>

    <div data-role="content" align="center">



        <!--<form action="View_Search_Results_Table.php" method="post" align="center"> -->
            <input type="text" name="deletepost" placeholder="Enter ISBN you want to delete">
            <input type="submit" name="delete" value="Delete Post"><br><br>

            <div style="overflow-x:auto;">
                <table border="1px solid black;" align="center">
                    <tr>
                        <th>Book ID</th>
                        <th>ISBN</th>
                        <th>Title</th>
                        <th>Author</th>

                    </tr>
            </div>


            <!-- populate table from mysql database -->
            <?php while($row = mysqli_fetch_array($search_result)):?>
                <tr>
                    <td><?php echo $row['Book_id'];?></td>
                    <td><?php echo $row['ISBN'];?></td>
                    <td><?php echo $row['Title'];?></td>
                    <td><?php echo $row['Author'];?></td>
                </tr>
            <?php endwhile;?>
            </table>


        <div data-role="footer" data-position="fixed" data-id="nav" data-theme="b">
            <div data-role="navbar">
                <ul>
                    <li><a href="Home_Page.php" data-icon="home" class="ui-btn-active ui-state-persist"></a></li>
                    <li><a href="#anylink" data-icon="alert"></a></li>
                    <li><a href="#anylink" data-icon="mail"></a></li>
                    <li><a href="Manage_User_Accounts.php" data-icon="gear"></a></li>
                </ul>
            </div>
        </div>

</body>
</html>

【问题讨论】:

    标签: php html sql phpmyadmin


    【解决方案1】:
    <form method="post" action="delete.php">
    
    <input type="text" placeholder="Enter the book ID to delete" name="getdeleteid">
    
    <button type="submit" value="Delete book">
    
    </form>
    

    PHP:

    <?php 
    
    $getdelete = $_POST['getdeleteid'];
    
        $pdo = new PDO('mysql:host=yourhost;dbname=nextbook ','user','password');
        $statement = $pdo->prepare("DELETE FROM books WHERE book_ID = ".$getdelete."");
        $statement->execute(array(1)); 
    
    
    ?>
    

    【讨论】:

    • 它说“警告:mysqli_fetch_array() 期望参数 1 是 mysqli_result,对象在 C:\xampp\htdocs\ITSS4312\mwa4\Manage_Posts.php 第 93 行给出”第 93 行现在是第一个这行: php echo $row['ISBN'];?>
    • 我不确定,删除代码没问题,你的错误似乎是,你没有得到任何结果,很难看到错误,因为我看不到你的整个代码
    • 我正在尝试创建一个显示表格的表格,以便用户可以看到要删除的书。我是否把“$query =”SELECT * FROM 'books'”;” Delete SQL 语句上方的语句,或者在 if 中,还是在之后?
    • 嗯.. 删除操作应该在另一个 php 页面上执行或使用 ajax.. 但你不应该在同一个文件中运行它。否则我不确定 POST 是否正常工作
    【解决方案2】:

    您应该将脚本分解为多个部分,以使视图更易于使用。此外,您应该将所有类都放在它们自己的页面中,并使用自动加载器(spl_autoload_register() 或类似的)来自动加载类。我已将所有内容放在一个页面上,看起来比实际复杂。最后,在表单中使用动作词来告诉您的程序您正在尝试做某事是很有帮助的:

    <?php
    /*
    **  @description    It's helpful to have a class that just does some general "stuff"
    **                  that all classes could potentially use
    */
    class App
        {
            protected   static $singleton;
    
            public  function __construct()
                {
                    if(!(self::$singleton instanceof \App))
                        self::$singleton    =   $this;
    
                    return self::$singleton;
                }
    
            # Retrieve the $_POST array or a key from it
            public  function getPost($key=false)
                {
                    if(!empty($key))
                        return (isset($_POST[$key]))? $_POST[$key] : false;
    
                    return $_POST;
                }
        }
    /*
    **  @description    It's helpful to have a database class for consistent database retrieval and querying
    */
    class Database extends \App
        {
            protected   static  $con;
            protected   $query;
            # Create and retrieve database connection
            public  function getConnection()
                {
                    # Create connection if not already set
                    if(!(self::$con instanceof \PDO))
                        self::$con  =   new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME,DB_USER,DB_PASS);
                    # Return the connection
                    return self::$con;
                }
            # Query database
            public  function query($sql,$bind=false)
                {
                    # Bind parameters for public requests
                    if(!empty($bind)) {
                        foreach($bind as $key=>$value) {
                            $bKey           =   ":{$key}";
                            $bArray[$bKey]  =   $value;
                        }
                    }
                    # Prepare sql
                    if(!empty($bArray)) {
                        $this->query    =   $this->getConnection()->prepare($sql);
                        $this->query->execute($bArray);
                    }
                    else
                        # Do a straight query
                        $this->query    =   $this->getConnection()->query($sql);
                    # Send back the object for chaining
                    return $this;
                }
            # Use with the query to retrieve database results
            public  function getResults()
                {
                    while($row = $this->query->fetch(\PDO::FETCH_ASSOC)) {
                        $new[]  =   $row;
                    }
    
                    return (!empty($new))? $new : false;
                }
        }
    
    /*
    **  @description    Because you are wanting to get database info, may as well extend the Database class
    **                  and use it's querying features
    */
    class Books extends Database
        {
            # Retrieve one or more books
            public  function getBook($id = false,$type='Book_id')
                {
                    $id     =   trim($id);
                    $sql    =   "SELECT * FROM `books`";
                    if(!empty($id)) {
                        $sql        .=  " WHERE `{$type}` = :0";
                        $results    =   $this->getConnection()->query($sql,array($id))->getResults();
                        return (is_array($results) && count($results) == 1)? $results[0] : $results;
                    }
    
                    return $this->getConnection()->query($sql)->getResults();
                }
            # Delete book
            public  function deleteBook($id,$type='ISBN')
                {
                    $this->getConnection()->query("DELETE FROM books WHERE `{$type}` = :0",array($id));
                }
        }
    
    class View extends Database
        {
            public static function createSrc($path,$type='js')
                {
                    if($type == 'js')
                        return '<script type="text/javascript" src="'.$path.'"></script>';
                    elseif($type == 'css')
                        return '<link rel="stylesheet" href="'.$path.'" />';
                }
        }
    
    
    # Should put these defines into a config.php file that you load at the top of every page
    define('DB_HOST','localhost');
    define('DB_NAME','nextbook');
    define('DB_USER','root');
    define('DB_PASS','');
    session_start();
    
    # Create instance of Books
    $App    =   new Books();
    # Creaet the book list (could be based on the search)
    $search =   $App->getBook($App->getPost('search'));
    # Check if the user is trying to delete a book
    if($App->getPost('action') == 'delete_isbn') {
        $App->deleteBook($App->getPost('deletepost'));
    }
    
    ?><!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8" >
    <?php echo View::createSrc('http://html5shiv.googlecode.com/svn/trunk/html5.js') ?>
    <?php echo View::createSrc('http://ie7-js.googlecode.com/svn/version2.1(beta4)/IE9.js') ?>
    <?php echo View::createSrc('http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css','css') ?>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <?php echo View::createSrc('http://code.jquery.com/jquery-1.11.1.min.js') ?>
    <?php echo View::createSrc('http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js') ?>
    <style>
    table {
        border-collapse: collapse;
        width: 30%;
    }
    
    th, td {
        text-align: left;
        padding: 5px;
    }
    
    tr:nth-child(even){background-color: #f2f2f2}
    
    th {
        background-color: #007d5f;
        color: white;
    }
    </style>
    <link rel="stylesheet" href="NextBook1.css"/>
    </head>
    <body>
    <div data-role="page" id="Manage_Posts">
        <div data-role="header" data-theme="b">
            <h1>NextBook</h1>
            <a href="Login.php" data-icon="power" class="ui-btn-right" data-theme="a" data-mini="true">Sign Out</a>
        </div><br>
        <div class="logo" align="center">
            <img src="Images/image1%20-%20Copy.PNG" width="100" height="100" />
        </div>
        <div data-role="content" align="center">
            <form action="" method="post" align="center">
                <input type="hidden" name="action" value="delete_isbn" />
                <input type="text" name="deletepost" placeholder="Enter ISBN you want to delete">
                <input type="submit" name="delete" value="Delete Post">
            </form>
            <br /><br />
            <table border="1px solid black;" align="center">
                <tr>
                    <th>Book ID</th>
                    <th>ISBN</th>
                    <th>Title</th>
                    <th>Author</th>
                </tr>
                <!-- populate table from mysql database -->
                <?php foreach($search as $row) { ?>
                <tr>
                    <td><?php echo $row['Book_id'];?></td>
                    <td><?php echo $row['ISBN'];?></td>
                    <td><?php echo $row['Title'];?></td>
                    <td><?php echo $row['Author'];?></td>
                </tr>
                <?php } ?>
            </table>
            <div data-role="footer" data-position="fixed" data-id="nav" data-theme="b">
                <div data-role="navbar">
                    <ul>
                        <li><a href="Home_Page.php" data-icon="home" class="ui-btn-active ui-state-persist"></a></li>
                        <li><a href="#anylink" data-icon="alert"></a></li>
                        <li><a href="#anylink" data-icon="mail"></a></li>
                        <li><a href="Manage_User_Accounts.php" data-icon="gear"></a></li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
    </body>
    </html>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-01
      • 2019-12-01
      • 1970-01-01
      • 2021-10-19
      • 1970-01-01
      • 2020-05-19
      • 2019-08-09
      • 1970-01-01
      相关资源
      最近更新 更多