PHP创建动态WHERE子句

时间:2018-05-20 16:41:55

标签: php

我正在创建一个可以使用WHERE子句动态搜索数据库的php。但是我在中途遇到了这个错误:

mysqli_fetch_assoc()期望参数1为mysqli_result,布尔值在

中给出

我尝试使用SELECT在表格中显示mysqli_fetch_assoc()结果。我认为使用mysqli_fetch_assoc()会将结果返回到数组中,因此可以用于在表格中显示,但显然现在不能正常工作......

我的PHP:

for ($i=1; $i<=5; $i++){
        if (isset($_POST["Q".$i])){
            ${"Q".$i} = $_POST["Q".$i];
            ${"Q".$i} = sanitise_input(${"Q".$i});
        }
    }

    $whereParts = array();
    if($Q1) { $whereParts[] = "firstname LIKE '%$Q1%' ";}
    if($Q2) { $whereParts[] = "lastname LIKE '%$Q2%' ";}
    if($Q3) { $whereParts[] = "student_number = ? ";}
    if($Q4) { $whereParts[] = "attempt_number = ? ";}
    if($Q5) { $whereParts[] = "attempt_score = ? ";}

    $query = "SELECT firstname, lastname, student_number, attempt_number, attempt_score FROM attempts ";
    if(count($whereParts)) {
        $query .= "WHERE " . implode('AND ', $whereParts);
    }
    $stmt = mysqli_prepare($conn, $query);
    @mysqli_stmt_bind_param($stmt, 'sssss', $Q1, $Q2, $Q3, $Q4, $Q5);

    mysqli_stmt_execute($stmt);
    if(!$stmt){
        echo "<p>Something is wrong with ", $query, "</p>";
    } else {
        echo "<table border =\"1\" id='result_table'>";
        echo "<tr>"
            ."<th scope=\"col\">First Name</th>"
            ."<th scope=\"col\">Last Name</th>"
            ."<th scope=\"col\">Student ID</th>"
            ."<th scope=\"col\">Attempt number</th>"
            ."<th scope=\"col\">Attempt score</th>"
            ."</tr>";
        $a = mysqli_stmt_get_result($stmt);
        while ($row = mysqli_fetch_assoc($a)){
            echo "<tr>";
            echo "<td>", $row["firstname"], "</td>";
            echo "<td>", $row["lastname"], "</td>";
            echo "<td>", $row["student_number"], "</td>";
            echo "<td>", $row["attempt_number"], "</td>";
            echo "<td>", $row["attempt_score"], "</td>";
            echo "</tr>";
        }
        echo "</table>";

我的HTML:

<label for="fName">First name</label>
<input type="text" id="fName" name= "Q1"/>

<label for="lName">Last name</label> 
<input type="text" id="lName" name= "Q2"/>

<label for="id">Student ID</label> 
<input type="text" id="id" name= "Q3"/>

<label for="Q4">Attempt</label>
<select id="Q4" name="Q4">
    <option value="">Please Select</option>
    <option value="1">First Attempt</option>
    <option value="2">Second Attempt</option>
    <option value="3">Third Attempt</option>
</select>

<label for="Q5">Score</label>
<select id="Q5" name="Q5">
    <option value="">Please Select</option>
    <option value="100">100%</option>           
    <option value="80">80%</option>
    <option value="60">60%</option>
    <option value="40">40%</option>
    <option value="20">20%</option>
    <option value="0">0%</option>
</select>

我哪里错了?

编辑:我发现了问题。因为我在mysqli_stmt_bind_param中有Q1到Q5,我需要输入所有5来获取一行,这不符合我想要的方式......

0 个答案:

没有答案