When I search item from database works fine,but How to prevent submitting search form when search field is empty? And get Fatal error : call to member function fetch_assoc() on string. Even if there is no item match in the database my function doesn’t return error message which I expect “Your search can not be found”.
<?php
include’lib/Session.php’>
Session::int();
Include’lib/Database.php’;
Include’helpers/Format.php’;
Spl_autoload_register(function ($class){
Include_once”Classes/“.$class.”.php”;});
$db = new Database();
$sr = new Search();
?>
<div class=”search”>
<form name=“form1” method=“post” action=“search.php”>
<input name=“search” type=“text” value=“Search for products”>
<input type=“submit” value=“Search”>
</form>
</div>
header.php
————————————————
<?php include’inc/header.php’;?>
<?php
If($_SERVER[‘REQUEST_METHOD’]== ‘POST’])
{ $search = $_POST[‘search’];
$getsr = $sr->search($search)
}
?>
<div class = “ section “>
<?php
If (isset ($getsr))
{
while($result = $getsr->fetch_assoc())
{
?>
<div class =“ grid “>
<a href=“details.php?proid=<?php echo $result[‘productId’];?><img src=“admin/<?php echo $result[‘image’];?>” alt=“”/></a>
<h2><?php echo $result[‘productName’];?></h2>
<p><?php echo $fm->textShorten($result[‘body’],60);?></p>
<p><?php echo $result[‘price’];?></p>
<div class=“button”><a href=“details.php?proid=<?php echo $tesult[‘productId’];?>”Details</a></div>
</div>
<?php } } ? >
</div>
search.php
———————————————————
<?php
$filepath = realpath(dirname(FILE));
Include_once($filepath.’/…/lib/Database.php’);
Include_once($filepath.’/…/helpers/Format.php’);
?>
<?php
Class Search{
Private $db;
Private $fm;
Public function __construct()
{ $this->db = new Database();
$this->fm = new Format();
}
Public function search ($search)
{ $search = $this->fm->validation($search);
$search = mysql_real_escape_string($this->dB->link,$search);
If(empty($search))
{ $searchmsg = “Search field must not be empty”;
return $searchmsg;
}
else {
$query = “ SELECT * FROM tbl_product WHERE productName LIKE ‘% “.$_POST[‘search’]. “ %’ “;
$result = $this->db->select($query);
If ($result!= False){
return $result;
}
else{
$searchmsg = “Search result not found ”;
return $searchmsg;
}
}
}
}
?>
Search.php