I am trying to create a visible product list on html. I have gotten it to the point where I had all the products and details showing and a submit button with text box for search at the top that did nothing. I then tried to make the submit button for search work but now it’s only showing the text box and submit button and when a query is searched it doesn’t show anything except the URL updates. I am trying to get it to search through the Description Cell data in table Products but it’s not working properly.
Please help me get the search function to work properly.
Here is the code.
`<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<title>My First SQL Page</title>
<link rel="stylesheet" type="text/css" href="shopstyle.css" />
</head>
<body>
<h1>Products List</h1>
<?php
// include some functions from another file.
include('functions.php');
// if the user provided a search string.
if(isset($_GET['search']))
{
$searchString = $_GET['search'];
}
// if the user did not provide a search string, assume an empty string
else
{
$searchString = "";
}
$SqlSearchString = "%searchString%";
$safeSearchString = htmlspecialchars($searchString, ENT_QUOTES,"UTF-8");
echo "<form>";
echo "<input name = 'search' type = 'text' value = '$safeSearchString'/>";
echo "<input type = 'submit'/>";
echo "</form>";
// connect to the database using our function (and enable errors, etc)
$dbh = connectToDatabase();
$sql = "SELECT * FROM Products WHERE Description = ?";
// select all the products.
$statement = $dbh->prepare($sql);
$statement ->bindValue(1,$SqlSearchString,PDO::PARAM_STR);
//execute the SQL.
$statement->execute();
// get the results
while($row = $statement->fetch(PDO::FETCH_ASSOC))
{
// Remember that the data in the database could be untrusted data.
// so we need to escape the data to make sure its free of evil XSS code.
$ProductID = htmlspecialchars($row['ProductID'], ENT_QUOTES, 'UTF-8');
$Price = htmlspecialchars($row['Price'], ENT_QUOTES, 'UTF-8');
$Description = htmlspecialchars($row['Description'], ENT_QUOTES, 'UTF-8');
// output the data in a div with a class of 'productBox' we can apply css to this class.
echo "<div class = 'productBox'>";
echo "<img src = '/ProductPictures/$ProductID.jpg' />";
echo "$Description <br/>";
echo "$Price <br/>";
echo "</div> n";
}
?>
</body>
</html>`
I have tried updating my SQL query with no luck and I am not sure where the problem lies since the search worked perfect in the SQL database when I tried Select * From Products where description like %radio% and that worked.
2
Answers
Your code:
You do correctly wrap
$SqlSearchString
in%
signs before binding it to the parameter, but you used=
instead ofLIKE
in the query.You shuld use like for your parameter and add then % to the variable