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

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

Related

MySQL select query comma separated numbers filter result

My table look like this:
Table screenshot
Here I'm getting the result by query:
$subject_ids = implode(',', $_POST['subject_ids'])
SELECT * FROM table WHERE focusarea LIKE '%$subject_ids%' ;
The result is perfect, but there is nothing to display when I select more than one subject ids, like if selecting only one then it shows,
but when to select 1, 2, and 4, but there is nothing with this LIKE query...
How can I fix this?
Use implode like,
PHP
$subject_id_aray = explode(",",$_POST['subject_ids']);
$in_array_string = array();
foreach($subject_id_aray as $values){
$in_array_string[] = "'".$values."'";
}
MySql
$sql = "SELECT * FROM table WHERE focusarea in (".implode(",",$in_array_string).") ;";
LIKE clause will not work in your case because using LIKE '%1,2,3%' in query will not get anything, as you as using Ids you should use IN instead of LIKE. LIKE will be used separately for each id if it is string.
As you are getting $_POST['subject_ids'] as an array, query will be like
$subject_str = implode(',', $_POST['subject_ids']);
$sql = "SELECT * FROM table WHERE focusarea IN($subject_str)";
If your column focusarea is not integer then
$subject_str = "'".implode("','", $_POST['subject_ids'])."'";
$sql = "SELECT * FROM table WHERE focusarea IN($subject_str)";
Maybe you have bug in POST.
Try to echo, $subject_ids befor inject to SQL.
You focus are is simple string of numbers, connected by ,, but what you are sending by POST maybe is not correct.
Other problem, this don't look like you full code.
Provide you file, if this don't resolve problem.

php/mySQL: querying records by id from array?

i want to query several records by id like:
$ids = array(10,12,14,16,....);
the query would be something like:
select * from users where id=10 or id=12 or id=14 or id=16 ..
is it possible to query it in a more comfortable way like (compared to php):
select * from user where in_array(id, array(10,12,14,16))
thanks
You can use IN instead of OR clauses
select * from users where id IN (put_your_array_here)
Example:
select * from users where id IN (10,12,14,16);
Note:
According to the manual for MySQL if the values are constant IN
sorts the list and then uses a binary search. I would imagine that
OR evaluates them one by one in no particular order. So IN is
faster in some circumstances.
Related post
Try this.
$id = array(10,12,14,16,....);
$ids = join("','",$id);
$sql = "select * from user where id IN ('$ids')";
OR
$ids = implode(',', $id);
$sql = "select * from user where id IN ($ids)";
You can do it like that using implode in PHP:
"select * from users where id in '".implode("','", $ids)."'"
Please be sure that your ids are safe though

using where statement with a sequence of ids

In my table, I have a column that it has a set of users id. its name is users_id.
each id separated with a comma(,).
ex : users_id = '1,2,3,4,5';
if I passed $id=1 to my function, how can I using where statement ?
function($id){
$sql = "select * from content_noti
where ??????"
}
You can add a leading and a trailing , in the field value in DB.
e.g.
Change
1,2,3,4,5
to
,1,2,3,4,5,
So that every Id has leading and trailing comma ,
Now, update the function body:
function($id){
$sql = "select * from content_noti
where users_id LIKE '%,$id,%'"
}
In this case you don't have any possibility of mistake as if you search user id 1 then you will get only 1 and not 11 or 111 or 1343.
Working Demo
if you have multiple ids than it would be better to use IN with query
$sql = "select * from content_noti where id IN (?)"
if you are looking for reverse than use find_in_set
$sql = "select * from content_noti where FIND_IN_SET(?, id)";
You can use regular expressions in mysql:
function($id){
$sql = "SELECT * FROM content_noti WHERE users_id REGEXP '(^|,)" . $i . "($|,)'";
}
SELECT * from content_noti where users_id = "1" OR users_id = LIKE '%1,%' OR users_id = LIKE '%,1%'
Storing multiple chunks of data as a single comma seperated colum is really poor design for databases and if at all possible you should look into normalizing this by making a coupling table and joining on that.
The performance of the above query will be terrible and it'll be hard to maintain.

Convert String into MySQL Query

I have this string in PHP:
$str = 1,3,6,5
These numbers can change and the length of the set can change to more or less than four. I want to convert to a MySQL query like this in PHP:
$qry = mysql_query("SELECT * FROM tbl WHERE id = 1 or id = 3 or id = 6 or id = 5")
It should be easy, but I don't know how to do it.
I will be grateful for any help.
You could use IN.
$query = mysql_query("SELECT * FROM table WHERE id IN ($str)");
Make sure $str is validated first to prevent sql injection.

Use an array inside a query string

Im trying to pass an array that I already found by a query into another query. For example:
$first_query = "SELECT id FROM from Table WHERE user = '{$_SESSION['id'}'";
$result = mysql_query($first_query,$connection);
$ids = mysql_fetch_array($result);
This is where it gets tricky for me. I want to pass $ids into the next query.
$id_implode = implode(", ", $ids)
$second_query = "SELECT * FROM Table2 WHERE id = '{$id_implode}';
The second query doesnt seem to be working. Any help is greatly appreciated!
your second query's syntax is wrong. Once evaluated it should read
select * from Table2 where id in (1,2,3)
ditch the curly braces and change the = to in. Don't use OR - that's a dumb way of ignoring good sql functionality
EDIT: Teneff's comment makes a very good point - why are you approaching the problem in this way? If there is a relationship between the tables they can be joined and all the data you want can be retrieved in a single query. If for some reason you can't / won't join the tables you could at least try a sub-query
select * from table2 where id in (select id from table where user = $_SESSION['id']);
To use a where statement with multiple entries to match on, use in ().
$id_implode = "'".implode("', '", $ids)."'"
$second_query = "SELECT * FROM Table2 WHERE id in ({$id_implode});
I think you should use IN
$id_implode = implode(", ", $ids)
$second_query = "SELECT * FROM Table2 WHERE id IN '({$id_implode})';
This assumes that $ids is made of int of course, otherwise you have to enclose eache entry in quotes. that means
IN (6,7,8,9)//this doesn't need quotes
IN ('lemon', 'orange')//needs quotes
try to use the IN syntax:
$id_implode = implode("', '", $ids);
$second_query = "SELECT * FROM Table2 WHERE id in ('{$id_implode}');

Categories