I'm working on setting up a basic search query for my database and returning it to a table. I'm running into an issue with the syntax to use within prepared statements.
I based my initial setup on a w3schools example.
The search input comes from a form on an html page
. This calls the php file
.
Within the php file
, I connect to the SQL server
and execute the following:
$search = $_POST['search'];
$stmt = $link->prepare("SELECT lname, fname FROM planner WHERE lname LIKE ?");
$stmt->bind_param('s', $search);
$stmt->execute();
$result = $stmt->get_result();
print_r($result);
if ($result->num_rows > 0) {
echo "<table><tr><th>Last Name</th><th>First Name</th></tr>";
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["lname"]."</td><td>".$row["fname"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
The challenge I'm running into is how to define the parameters
for the LIKE to evaluate within the prepared statement construct. W3Schools give lots of examples of LIKE parameters
using various combinations of letters and %
, but I'm not sure where to put these in the prepared statement. I want to base the lname results on the search criteria provided from the form on the html page.
Several old posts on this site point to setting the criteria within a string. I'm not sure exactly how it works. If that's a good way to go about it, I'd like to know more about what's going on with this method.
Appreciate any help you all can provide.
I want to thank everyone for their help with this. ArtisticPhoenix got me headed in the right direction.
This post hit the mark of what I was looking for to bring it all together:
Adding a wildcard character to a string in PHP
Here's the "slightly" updated code:
$search = $_POST['search'].'%';
//echo($search);
$stmt = $link->prepare("SELECT lname, fname FROM planner WHERE lname LIKE ?");
$stmt->bind_param('s', $search);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
echo "<table><tr><th>Last Name</th><th>First Name</th></tr>";
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["lname"]."</td><td>".$row["fname"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With