I have a simple search form
, which I use to send a POST
request to my php script using AJAX. I want the script to search my database for the keyword in the title column, and return the rows where it finds it. The posted data looks like this "searchword=test1"
, where test1
in the content of my text input.
I have 2 rows in my database, one has a title of test1, and another of test2. If I do SELECT * FROM articles
I can see the results fine. If I type SELECT * FROM articles WHERE title LIKE 'test1';
into console, I get the correct result, but my php script returns an empty array.
No idea what I'm doing wrong here, any help is appreciated.
my php:
try {
$hostname = "localhost";
$username = "root";
$password = "";
$db = new PDO("mysql:host=$hostname;dbname=topdecka_PTC",$username, $password);
if (!empty($_POST["searchword"])) {
$searchword = $_POST["searchword"];
$query = $db->prepare("SELECT * FROM articles WHERE title LIKE %:seachword%");
$query->execute(array(':searchword' => $searchword));
$result = $query->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($result);
die();
}
else {
$query = $db->prepare('SELECT * FROM articles');
$query->execute();
$result = $query->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($result);
die();
}
} catch (PDOException $e) {
echo "Error!: " . $e->getMessage() . "<br/>";
die();
}