I've inherited some PHP scripts from a colleague and one is used for searching the "Notes" text field of a database called "Sheep" via a text box:
Code for the search box:
<h2>Find sheep Notes</h2>
Please note this looks at both sheeps and lambs.
<form method="post">
<label for="sheep"><br>Enter text in the box</label>
<input type="text" id="sheep" name="sheep">
<input type="submit" name="submit" value="View Results">
However when anything is searched it currently shows the following error:
SELECT *, DATE_FORMAT(DOB, '%d-%m-%Y') AS DOB, DATE_FORMAT(`Record started Date`, '%d-%m-%Y') AS `Record started Date`, FROM Sheep, WHERE `Notes` LIKE '%section%'
SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
No results found for section.
I don't know PHP well at all but below is the PHP code. All I know is that it needs to be able to search the text field called "Notes" for any string of text using the wildcard syntax:
<?php
//error_reporting(-1);
//ini_set('display_errors', 'On');
if (isset($_POST['submit'])) {
try {
require "./config.php";
require "./common.php";
$connection = new PDO($dsn, $username, $password, $options);
$notes = $_POST['sheep'];
$sql = "SELECT *,
DATE_FORMAT(DOB, '%d-%m-%Y') AS DOB,
DATE_FORMAT(`Record started Date`, '%d-%m-%Y') AS `Record started Date`
FROM Sheep
WHERE `Notes` LIKE '%$notes%'";
$sheep = $_POST['sheep'];
$statement = $connection->prepare($sql);
$statement->bindParam(':sheep', $sheep, PDO::PARAM_STR);
$statement->execute();
$result = $statement->fetchAll();
} catch(PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
}
?>
Can anyone advise where this is wrong? I've done some research but after many attempts at fixing it I've not been able to.
CodePudding user response:
You should replace $notes
in the query with :sheep
. Then concatenate the wildcard characters to to $sheep
.
$connection = new PDO($dsn, $username, $password, $options);
$sql = "SELECT *,
DATE_FORMAT(DOB, '%d-%m-%Y') AS DOB,
DATE_FORMAT(`Record started Date`, '%d-%m-%Y') AS `Record started Date`
FROM Sheep
WHERE `Notes` LIKE :sheep";
$sheep = '%' . $_POST['sheep']. '%';
$statement = $connection->prepare($sql);
$statement->bindParam(':sheep', $sheep, PDO::PARAM_STR);
$statement->execute();