I have built a basic search engine which is almost functional. I am using UNION
in the query in order to search for an specific value in two tables blog
and pages
. I am also using PDO style. There are a total of 13 rows. When I perform the query with keyword blah
which is found in every column of both tables. I only get 5 results back from SELECT COUNT(*) FROM blog
and nothing back from SELECT COUNT(*) FROM pages
. Also I am using a prepare statement for :searchquery => $serachquery
that stores the keyword value but when echoing the value I get :searchquery
instead of blah
. How can I display the correct results? DEMO
PHP
<?php
include("db_con/db_con.php");
$search_output = "";
if(isset($_POST['searchquery']) && $_POST['searchquery'] != ""){
$searchquery = preg_replace('#[^a-z 0-9?!]#i', '', $_POST['searchquery']);
if($_POST['filter1'] == "All Tables"){
$sqlCommand = "(SELECT COUNT(*) FROM blog WHERE blog_title LIKE :searchquery OR blog_body LIKE :searchquery) UNION (SELECT COUNT(*) FROM pages WHERE page_title LIKE :searchquery OR page_body LIKE :searchquery) ";
}
$sql_prepare = $db_con->prepare($sqlCommand);
if($sql_prepare->execute( array("searchquery"=>'%'.$searchquery.'%') )){
$count = $sql_prepare->fetchColumn();
if($count > 1){
$search_output .= "<hr />$count results for <strong>$searchquery</strong><hr />$sqlCommand";
} else {
$search_output = "<hr />0 results for <strong>$searchquery</strong>$sqlCommand<hr />";
}
}
}
?>
HTML
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Search For:
<input name="searchquery" type="text" size="44" maxlength="88">
Within:
<select name="filter1">
<option value="All Tables">All Tables</option>
</select>
<input name="myBtn" type="submit">