如何将这段代码更改为PHP准备的语句

时间:2018-10-18 12:36:53

标签: php mysqli prepared-statement

这是我进行分页以显示数据库中我的画廊的代码。现在,我需要将此代码转换为Prepared Statements,这对Prepared Statement是新手。我真的很困惑如何在此使用准备好的语句。正如我提到的那样,我对准备好的语句并不陌生,但是现在我开始通过$ stmt-> fetch()语句使用准备好的语句进行查询,我现在不知道如何分页。

<?php
    $limit = 2;
    if(isset($_GET["page"])) {
        $page = $_GET["page"];
    } else {
        $page = 1;
    }
    ;
    $start_from = ($page - 1) * $limit;
    $sql = "SELECT * FROM album_catagories ORDER BY id DESC LIMIT $start_from, $limit";
    $rs_result = mysqli_query($connection, $sql);
?> 
<div class="full-gallery">
    <h3>Gallery</h3>
    <div class="row">
        <div class="content">
            <?php
                while($image = mysqli_fetch_assoc($rs_result)) {
                    echo '
                    <div class="album_holder">
                        <img id="myImg" src ="includes/uploads/images/gallery/' . $image['coverimage'] . '" class="gallery-image">
                        <p>' . $image['title'] . '</p>
                        <a id="purple-button" href="viewalbum.php?album=' . $image['id'] . '">View Album</a>
                    </div>';
                }
            ?> 
        </div>
    </div>
    <div class="pag-menu">
        <?php
            $sql = "SELECT COUNT(id) FROM album_catagories";
            $rs_result = mysqli_query($connection, $sql);
            $row = mysqli_fetch_row($rs_result);

            $total_records = $row[0];
            $total_pages = ceil($total_records / $limit);
            $pagLink = "<nav><ul class='pagination'>";

            for($i = 1; $i <= $total_pages; $i++) {
                $pagLink .= "<li><a href='gallery.php?page=" . $i . "'>" . $i . "</a></li>";
            }
            ;
            echo $pagLink . "</ul></nav>";
        ?>
    </div>
</div>
<?php include('footer.php'); ?>

1 个答案:

答案 0 :(得分:0)

我认为这会给您准备的陈述和答复

<?php
    $limit = 2;
    if(isset($_GET["page"])) {
        $page = $_GET["page"];
    } else {
        $page = 1;
    }
    ;
    $start_from = ($page - 1) * $limit;
    $sql = "SELECT * FROM album_catagories ORDER BY id DESC LIMIT ?, ?";
    $stmt = mysqli_prepare($connection,"SELECT * FROM album_catagories ORDER BY id DESC LIMIT ?, ?");
    mysqli_stmt_bind_param($stmt,$start_from,$limit);
    $rs_result = mysqli_stmt_execute($stmt);
?>