0

I am a new in PHP, and I have some question regarding select statement using IN parameters.

<?php

$resultID = "333\n334\n335\n0";

$reconResult = str_replace("\n",",",$resultID);

//$reconResult will display 333,334,335,0

$query = mysql_query('SELECT * FROM tbl_name WHERE tbl_item_id IN($reconResult)');

if(mysql_num_rows($query)>0){
     while($r=mysql_fetch_object($query)){
         echo $r->tbl_item_name;
     }
}

?>

I only want to display the items which contains id's from $reconResult;

Thanks in advance.

leojarina
  • 157
  • 4
  • 15
  • Why are you creating an LF separated string, only to replace the LFs with commas? Why just create it with commas in the first place? There is (probably) nothing wrong with above code - what problem are you having? The only problem I can see is that you *may* need a space between the `IN` and the `(` in the query. **EDIT** And the fact that you need to double quote the string, as @Jelle De Laender correctly points out... – DaveRandom Apr 03 '12 at 09:53

2 Answers2

7

$query = mysql_query('SELECT * FROM tbl_name WHERE tbl_item_id IN($reconResult)');

PHP isn't changing variables within ', only in " blocks.

Try

$query = mysql_query("SELECT * FROM tbl_name WHERE tbl_item_id IN($reconResult)");

or

$query = mysql_query('SELECT * FROM tbl_name WHERE tbl_item_id IN('.$reconResult.')');

Best way to check this is by setting the whole SQL as a string, eg $str = "SELECT * .."; and printing this var.

Jelle De Laender
  • 577
  • 3
  • 16
0

Try

$query = mysql_query("SELECT * FROM tbl_name WHERE FIND_IN_SET(tbl_item_id, '{$reconResult}')");

http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_find-in-set
also see: FIND_IN_SET() vs IN()

Community
  • 1
  • 1
fragmentedreality
  • 1,287
  • 9
  • 31
  • if the result returns $reconResult will display 335,334,333,0 it returns into false. How I am gonna fix this? Thanks – leojarina Apr 04 '12 at 01:48
  • You can set the result in single-quotes `'` – the same way I edited my answer. And mind the double-quotes around the whole query, as @Jelle pointed out, PHP does not resolve variables within single-quotes. – fragmentedreality Apr 04 '12 at 07:48