Solution 1 :

The variable $id which you bind to the query is not initialized.

You want to search for “First name” therefore you need to use the variable $firstname in your query.

// Check if formular is send and $_POST['firstname'] is set
if (isset($_POST['firstname'])) {
    // Escaping is not neccessary because you use prepared statements!
    $firstname = $_POST['firstname'];
    $sql = "SELECT * FROM usersthree WHERE firstname=?";
    $stmt = $conn->prepare($sql); 
    $stmt->bind_param("s", $firstname);
    $result = $stmt->get_result(); // get the mysqli result
    $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!";
    }
}

Problem :

I set up an input form in which I use the SELECT function in order to search the table for existing users, and so it will display the user’s name and email. But when I try, I get “No users with name John!” even though there is a user named John in the table. Why does the prepared statement not work?
addpreparedstatement.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!";
        }
?>

Comments

Comment posted by s1mplet0n

When I tried your solution, I recieved this error message: Uncaught Error: Call to a member function bind_param() on bool. Do you know the cause of this error occurring?

By