I am almost finished my project but have spent most of my time trying to get a value from the search box into a mysqli query. The program works perfectly when I hardcode the value into the query as in the example below..

 $result = $mysqli->query("SELECT * FROM data WHERE classroom = '107i am'");  

When I have tried classroom ='$classroom'. I get error messages such as..

Notice: Undefined variable: result in D:\xampp\htdocs\reports\index.php on line 190
Fatal error: Uncaught Error: Call to a member function fetch_assoc() on null in D:\xampp\htdocs\reports\index.php:190 Stack trace: #0 {main} thrown in D:\xampp\htdocs\reports\index.php on line 190

Line 190 contains while ($row = $result->fetch_assoc()): ?>
Somehow it has no value for $result

<form method="POST" action="index.php<?php echo $_SERVER['PHP_SELF'];?>">
   Enter Class Name: <input type="text" name="classroom">
   <input type="submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $classroom = $_POST['classroom'];
    if (empty($classroom)) {
        echo "classname is empty";
    } else {
            $result = $mysqli->query("SELECT * FROM data WHERE classroom = '$classroom'");         
} } ?>

It's probably an easy fix for you guys, but I'm getting nowhere.
Many thanks for your guidance.

[Mod: added [code]...[/code] tags; note for future reference.]

1) Use parameter binding to put user-supplied data into queries.
2) If $classroom is empty then $result is never given a value. So it's null. So then why would you be trying to fetch rows from it?

Write a Reply...