0

This works fine except for the first time I open the page and nothing is in the search button. Then I get an error, along with all of the results displayed instead of only when searching:

Undefined variable: searchTerm in C:\xampp\htdocs\index3.php on line 77

<?php

if (isset($_POST['search'])) {
    $searchTerm = $_POST['search'];
}
            
$conn = new mysqli("localhost", "root", "", "Assignment_11");
if ($conn->connect_error) {
    echo 'Connection Faild: '.$conn->connect_error;
} else {
    $sql = "select * from Items where name like '%$searchTerm%'";

    $res = $conn->query($sql);

    while ($row = $res->fetch_assoc()) {
        echo "<br> Name: ". $row["name"]. "   Type: ". $row["type"].  "  Brand:  ".  $row["brand"]. "<br>";
    }
}
Dharman
  • 30,962
  • 25
  • 85
  • 135
fili009
  • 9
  • 1
  • **Warning:** You are wide open to [SQL Injections](https://stackoverflow.com/a/60496/1839439) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187) – Dharman Aug 05 '20 at 22:43
  • If `$_POST['search']` is required then you should return an error response whenever it is not set. If it's not required you should check if `$searchTerm` is set before using it – apokryfos Aug 05 '20 at 22:51

0 Answers0