xkeshav
xkeshav

Reputation: 54016

How to get data when we provide multiple value of a field

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

Upvotes: 1

Views: 93

Answers (3)

gregseth
gregseth

Reputation: 13408

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)";

Upvotes: 0

Doug Neiner
Doug Neiner

Reputation: 66191

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)";

Upvotes: 1

AJ.
AJ.

Reputation: 28174

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

Upvotes: 5

Related Questions