如何在我的评论打印系统中添加准备语句

How can I add prepare statement in my comment printing system

我目前正在构建一个用户可以撰写和阅读评论的系统。所以评论会被插入到数据库中(插入部分已经被prepared statement保护),所以现在我想在评论打印部分也添加prepared statement。

这是评论插入部分

<?php
    if (isset($_POST['submit'])) {
    $nickname=$_POST['user_nickname'];
    $email=$_POST['user_email'];
    $comment=$_POST['cmt_text'];
    $course=$_POST['user_course'];
    $rating=$_POST['user_rating'];
    $classof=$_POST['user_classof'];
    $school_id=$_POST['id'];
    $db="INSERT INTO comments(user_nickname,user_email,cmt_text,user_course,user_rating,school_id,user_classof) VALUES(?,?,?,?,?,?,?)";
    $stmt=mysqli_stmt_init($con);
    if(!mysqli_stmt_prepare($stmt,$db)){
        echo "Data Error";
    }else{
        mysqli_stmt_bind_param($stmt,"ssssiii", $nickname,$email,$comment,$course,$rating,$school_id,$classof);
        mysqli_stmt_execute($stmt);
    }
    header("location:Done.php");
    exit;
    }?>

这是我要添加准备好的语句的地方

<?php 
    $sql = "SELECT * FROM comments WHERE school_id=$sid ORDER BY Datetime DESC ";
    $result = mysqli_query($con, $sql);
    if (mysqli_num_rows($result) > 0) {
    while ($row = mysqli_fetch_assoc($result)) {
    ?>
        <div class="single-item">
            <h4><?php echo $row['user_nickname'];   ?></h4>
            <p><?php echo $row['Datetime']; 
            ?></p>
            <p><b>Course</b> : <?php echo $row['user_course']; 
            ?></p>
            <p><b>Class of</b> <?php echo $row['user_classof']; 
            ?></b></p>
            <p><b>Rating : </b><?php echo $row['user_rating']; 
            ?>/5</p>
            <p><b>Comment : </b><?php echo $row['cmt_text']; 
            ?></p>
        </div>
        <?php
            }
        }
?>

我试过添加,但是在需要添加参数的部分卡住了,因为我正在打印所有注释,所以如何添加?参数?

顺便说一句, $sid是一所学校的特定ID。 comments table有一百多所学校。我把每个学校的所有评论都放在一个 table.

只需创建一个函数,您将在其中准备数据。

function selectComments(mysqli $mysqli, ?int $schoolId = null): array
{
    if ($schoolId) {
        $stmt = $mysqli->prepare('SELECT * FROM comments WHERE school_id=? ORDER BY Datetime DESC');
        $stmt->bind_param('s', $schoolId);
        $stmt->execute();
        $result = $stmt->get_result();
    } else {
        $result = $mysqli->query('SELECT * FROM comments ORDER BY Datetime DESC');
    }
    return $result->fetch_all(MYSQLI_ASSOC);
}

那么你可以这样称呼它:

foreach(selectComments($con, $sid) as $row) {
    // your HTML table
}