Search box to display MySQL database results in a table?

I’m trying to build a web page which allows a user to search for a key term in a search box and have the result(s) display in a table if they match the database table called ‘stock’. The database has been created in phpmyadmin and just holds some basic records regarding a shop’s stock (dummy data, not real). Unfortunately I am having difficulty getting anything to display when I press search, and based on my current beginners knowledge I’ve put the following together.

HTML Snippet:

[code]

[/code]

PHP:
[php]<?php
$username = “”;
$password = “”;
$host = “”;
$db = “”;
$connection = mysqli_connect($host, $username, $password, $db);
if (mysqli_connect_error()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

echo "<table border=1>
<tr>
<th>Item ID</th>
<th>Product Name</th>
<th>Description</th>
<th>Stock</th>
<th>Style</th>
<th>Gender</th>
<th>Size</th>
<th>Price</th>
</tr>";

$search = $_POST["search"];

$query = "SELECT * FROM stock WHERE 'product_name' LIKE '%$search%'";
$result = mysqli_query($connection, $query);

if ($result) {
    while($row=mysqli_fetch_row($result)) {
        echo "<tr>";
        echo "<td>" . $row['item_id'] . "</td>";
        echo "<td>" . $row['product_name'] . "</td>";
        echo "<td>" . $row['description'] . "</td>";
        echo "<td>" . $row['stock_level'] . "</td>";
        echo "<td>" . $row['style'] . "</td>";
        echo "<td>" . $row['gender'] . "</td>";
        echo "<td>" . $row['size'] . "</td>";
        echo "<td>" . $row['price'] . "</td>";
        echo "</tr>";
    }
}
else {
    echo "No results to display";
}

mysqli_close($connection);

?>[/php]

In its current state I was trying to search only for key words in ‘product_name’ as opposed to the entire table, a full table search is something I’d like to be able to do once I can get the basic search functionality working. The web page successfully displays the text input box, search button, and table headings, but when I enter a string that I know is in my database table the search button does not return anything.

It would be great if anyone could tell me what I’m doing wrong, I’d imagine it’s something stupidly obvious as usual, apologies for any bad coding. Thanks.

Did you try running the query directly in Phpmyadmin? Turn on error reporting. There are several other minor issues with your code.

Take the quotes off product_name in the query.

Your code is Vulnerable to an SQL Injection Attack. You NEVER EVER send user supplied data to the DB. You need to use prepared statements. I suggest you use PDO as well.

https://phpdelusions.net/pdo

Sponsor our Newsletter | Privacy Policy | Terms of Service