1

I have a string of values like :

$cat = "1,5,6,8,9";

now I would like to use that variable in WHERE clause. how do I do it ?

"select category from test where category...?"

I am using below code but I get null from number_of_result variable :

$array_of_cat = explode(",",$cat);

if($number_of_result == 0){
    $mresult = mysql_query("select * from books where
     GoodName like '%$title%' and GroupCode in ($array_of_cat) ");
    $number_of_result = mysql_num_rows($mresult);
}
S.M_Emamian
  • 17,005
  • 37
  • 135
  • 254

3 Answers3

1

You do not need to explode the variable - doing so results in an array that will result in the wrong value (the string "Array") when interpolated into the SQL string.

Despite the fact that this is unsafe (SQL injection prone) you could do:

if($number_of_result == 0){
    $mresult = mysql_query("select * from books where
     GoodName like '%$title%' and GroupCode in ($cat)");
    $number_of_result = mysql_num_rows($mresult);
}

I strongly suggest you use the mysql_real_escape_string function to prepare your variables.

Community
  • 1
  • 1
sfitsos
  • 5
  • 2
1

Change your SQL statement to this one. Use implode() to pass array elements in IN clause

$mresult = mysql_query("
  SELECT * FROM books 
  WHERE GoodName LIKE '%$title%' AND GroupCode IN (" . implode(",", $array_of_cat) . ")");
hex494D49
  • 9,109
  • 3
  • 38
  • 47
0
$cat = array(1,5,6,8,9);

$array_of_cat = implode(",",$cat);

if($number_of_result > 0){
  $mresult = mysql_query("select * from books where
  GoodName like '%$title%' and GroupCode in ($array_of_cat) ");

$number_of_result = mysql_num_rows($mresult);
}

Also, I'd strongly suggest reading up on PDO/MySQLi