开发者

PHP query error

I am using LIKE to do my searching, i try it in phpMyAdmin and return the result but when i use it in php it return empty result.

$search = "ip";
$start = 0;
$query = "SELECT * FROM product WHERE product_name LIKE '%$search%' LIMIT $start,30";
$result = mysql_query($query);
if(empty($result))
    $nrows = 0;
else
    $nrows = mysql_num_rows($result);

It will return result when i using phpMyAdmin to run this query but when i use it in php, it return开发者_如何学编程 empty.

Update:

Sorry guys,

I just found out the problem is i didn't connect database as well. anyway, thanks for helping.


Try This

 $query = "SELECT * FROM `product` WHERE `product_name` LIKE '%".$search."%' LIMIT 0, 30";


And if the sole purpose of your code is to get the number of products with the searched-for name, use SELECT COUNT(*) instead of doing a mysql_num_rows() on all your data. It will decrease your querytime and the amount of data that is (unnecessarily) fetched.


I am not sure why this is not working, as the query seems to be correct to me. I would like to suggest you writing query this way

$query = <<<SQL

 SELECT * FROM product WHERE product_name LIKE "%$search%" LIMIT $start,30

SQL;

please note that there should not be any space or any character after SQL;


$query = "SELECT * FROM product WHERE product_name LIKE '%" . $search . "%' LIMIT " . (int) $start. ",30";


you can use directly mysql_num_rows()

but here is right code

$query = "SELECT * FROM product WHERE product_name LIKE '%".$search."%' LIMIT $start,30";


$search = "ip";
$start = '0';
$query = "SELECT * FROM product WHERE product_name LIKE '%".$search."%' LIMIT $start,30";
$result = mysql_query($query)or die(mysql_error());
if(mysql_num_rows($result) == 0){
    $nrows = 0;
} else{
    $nrows = mysql_num_rows($result);
}

//use mysql_num_rows($result) instead of empty($result) because in this situation $result is every time not empty so use inbuilt PHP function mysql_num_rows($result);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜