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.

1
  • 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... Commented Apr 3, 2012 at 9:53

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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()

2 Comments

if the result returns $reconResult will display 335,334,333,0 it returns into false. How I am gonna fix this? Thanks
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.