I’m trying to create a simple search function in php, the user inserts his search query in a textbox:
<form action="inc/search.inc.php" method="post">
<input id="searchbox" name="search" class="search" type="text"></input>
</form>
My search.inc.page redirects the user to an URL with the query:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST"
&& !empty($_POST["search"]))
{
$searchquery=$_POST["search"];
header("Location: ../search.php?qr=".$searchquery);
}
?>
My search.php calls the function retrieveSearch:
<?php
include_once 'inc/functions.inc.php';
include_once 'inc/db.inc.php';
$db2 = new PDO(DB_INFO, DB_USER, DB_PASS);
$qr = (isset($_GET["qr"])) ? (string) $_GET["qr"] : NULL;
$e2 = retrieveSearch($db2, $qr);
$qresult = array_pop($e2);
echo $qresult;
foreach ($e2 as $row)
{
echo $row["title"]."<br/> ";
}
?>
retrieveSearch function:
function retrieveSearch($db2, $qr=NULL)
{
$sql2 = "SELECT id, title, resume, search
FROM blog
WHERE search LIKE ?";
$stmt2 = $db2->prepare($sql2);
$stmt2->execute(array($_GET["qr"]));
$e2 = $stmt2->fetch();
array_push($e2, $qr);
return $e2;
}
Unfortunately, this is returning me some weird results, if for example I search for “fff” (one of my ‘search’ entries), I get the following:
fff3
3
f
f
<
<
f
f
The 3 infront of ‘fff’ is the id – which I have no clue where it came from, the other characters seem to be the first letter/symbol of every column… even though I specifically said I only wanted the “title” column displayed.
Look at documentation of PDOStatement::fetch
What happens: You fetch only the first row of results and then iterating over its columns. ‘title’ string is then converted to int (evaluated as zero) and result is the first character of each column.