php 预准备语句不显示用户数据

我设置了一个输入表单,在其中我使用 SELECT 函数在表中搜索现有用户,因此它将显示用户的姓名和电子邮件。但是当我尝试时,即使表中有一个名为John的用户,我也会得到“没有名为John的用户!”。为什么准备好的声明不起作用?添加准备语句.php


<?php

    include_once 'includes/db_connect.php';

?>

<!DOCTYPE html>

<html>

<head>

<title>SCIENCE FAIR</title>

<link rel="stylesheet" href="style.css">

    <section class ="container grey-text">

    <form class="white" action="addpreparedstatements.php" method="POST">

    <tr>

        <label>First Name:</label>

        <td><input type="text" name="firstname" placeholder="First Name"></td></br>

    </tr>

        <div class="center">

            <td colspan="2"><input type="submit" name="submit" value="Submit"></td>

        </div>

    </form>

</section>

</html>

<?php

    $firstname = mysqli_real_escape_string($conn, $_POST['firstname']);


    $sql = "SELECT * FROM usersthree WHERE id=?";

    $stmt = $conn->prepare($sql); 

    $stmt->bind_param("s", $id);

    $stmt->execute();

    $result = $stmt->get_result(); // get the mysqli result

    $user = $result->fetch_assoc(); // fetch data   

    $queryResult = mysqli_num_rows($result);


        if ($queryResult > 0) {

            while ($row = mysqli_fetch_assoc($result)) {

                echo "<div>

                <p>".$row['name']."<p>

                <p>".$row['email']."<p>

                </div>";

            }

        } else {

            echo "No users with name $firstname!";

        }

?>


有只小跳蛙
浏览 72回答 1
1回答

慕尼黑8549860

绑定到查询的变量未初始化。$id您想要搜索“名字”,因此您需要在查询中使用变量$firstname。// Check if formular is send and $_POST['firstname'] is setif (isset($_POST['firstname'])) {&nbsp; &nbsp; // Escaping is not neccessary because you use prepared statements!&nbsp; &nbsp; $firstname = $_POST['firstname'];&nbsp; &nbsp; $sql = "SELECT * FROM usersthree WHERE firstname=?";&nbsp; &nbsp; $stmt = $conn->prepare($sql);&nbsp;&nbsp; &nbsp; $stmt->bind_param("s", $firstname);&nbsp; &nbsp; $result = $stmt->get_result(); // get the mysqli result&nbsp; &nbsp; $queryResult = mysqli_num_rows($result);&nbsp; &nbsp; if ($queryResult > 0) {&nbsp; &nbsp; &nbsp; &nbsp; while ($row = mysqli_fetch_assoc($result)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; echo "<div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <p>".$row['name']."<p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <p>".$row['email']."<p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </div>";&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; echo "No users with name $firstname!";&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP