当我们提供字段的多个值时如何获取数据

I have 3 id in a string:

  let $x="6,3,5"

I want to get all color information from tbl_color where color id are

6, 3 and 5.

I made this query, but does not work. What's wrong with this?

$sql=" SELECT * FROM tbl_color WHERE color_id IN(".explode(',',$x).")

please suggest the right query

explode() takes a string and turns it into an array. You already have a string. All you need to do is change your statement and just include $x in your string. You don't need to explode it.


UPDATE:

Per your comment, here is how I would do it:

$x="3,4,5";
$sql=" SELECT * FROM tbl_color WHERE color_id IN(".$x.");";

HTH,

-aj

You are concatenating an array with a string. The explode is not needed:

$sql = "SELECT * FROM tbl_color WHERE color_id IN ($x)";

A full example assuming you get the input from a user or it is sent from the browser to the server:

$x = $_GET['colors']; // 6,3,5
$x = mysql_real_escape_string( $x ); // Prevent SQL Injection attack
$sql = "SELECT * FROM tbl_color WHERE color_id IN ($x)";

If $x is a string, then you don't need to use explode, just use it as is

$sql="SELECT * FROM tbl_color WHERE color_id IN($x)";