selecting the rows in mysql with arrays - php

In my db, i have a table, Timetable where one field is Subject.
It will hold value like this. For example. 1,2,3,4
Now,
I need to compare this field with my array named
$mysubs=array('1','3','5');
I have tried this.
select * from Timetable where Subject IN (".implode(',',$mysubs).");
But if I have only one value in subject field it is working. If it holding something 1,2,3 then it is not working. Is it possible to match using 'LIKE'. Plz help me

Try some thing like this if subject field value is comma separated.
$mysubs = array('1','3','5');
$whereSubClause = '';
for($i=0; $i < count($mysubs); $i++){
$whereSubClause .= 'FIND_IN_SET($i,subject) OR ';
}
// Remove the last OR
$whereSubClasue = substr($whereSubClause,0,-3);
// now query
select * from Timetable where $whereSubClause;
But if it is not comma separated do like this:
$values = implode("','",$mysubs);
"select * from Timetable where subject IN('".$values."');"

$values = implode(',',$mysubs);
$query = "select * from Timetable where Subject IN ($values)";
I use that in some of my projects and it works well
i also thinks it is better to separate query and php operations, at least for a better code readability

Try this query
$sql = "select * from Timetable where Subject LIKE '".implode(',',$mysubs)."%'";
It may help you.

This should work:
$mysubs = array(1, 3, 5);
$sql = "SELECT * FROM Timetable WHERE Subject IN (".implode(', ', $mysubs).");";
That should output this:
$sql = "SELECT * FROM Timetable WHERE Subject IN (1, 3, 5);";
It is generally good practice in SQL to capitalize parts of the language like SELECT, INSERT, or UPDATE. Also your array of values you are searching for in $mysubs were strings, though it is better to have them as integers.

You need to save the field with appending and prepending comma.
For example:
,1,2,3,4, OR ,11,12,23,45,
And you need to search for every array element.
$mysubs=array('1','3','5');
select * from Timetable where Subject LIKE '%,1,%' OR
Subject LIKE '%,3,%' Subject LIKE '%,5,%'

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.

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.

I want to select record multiple key with like

I want to select record from table with key.My code is working but it's not select all record regarding Php and Mysql it select only PHP,Mysql record.
My code is
$skill=PHP,Mysql;
mysql_query("select * from tablename(skill) where fieldname(key) like '%$skill%'");
Try to do this
mysql_query("select * from skill where (key like '%PHP%' OR key like '%Mysql%')");
As you have comma separated values in $skill variable like operator will not work correctly, try using following query
select * from skill where FIND_IN_SET(keyn,'$skill')
Demo sql fiddle at http://sqlfiddle.com/#!2/181c74/5
$skill="PHP,Mysql";
mysql_query("select * from skill where key like '%$skill%'");
I am assuming you want to search for records that contain "PHP", "MySQL", or both. What you're doing is searching for the exact string of "PHP,MySQL".
A quick and dirty solution would be to turn $skill into an array that is split on the commas and then perform the search for each term using the OR keyword.
For example:
$skill = array("PHP", "MySQL");
$query = "select * from tablename(skill) where ";
foreach ($skil in $skill)
$query . "fieldname(key) like '%$skil%' OR ";
//code to remove the OR at the very end
Use in into your Query
select * from `skills` WHERE skillslist in ('Php','Javascript')
Run demo Fiddle

One Select statement for criteria of one column with multiple values

I want to make a SQL SELECT statement that selects multiple rows based on the value of one column, but I have a list of valid values that match the rows I want to select.
Specifically, I have a list of user IDs. I want to select the entire row for every row that has a user id that is in this list (this list is in PHP, and I'm also making the SQL calls from there).
My code so far, looks like this:
$list_of_ids = array(1, 5, 7, 23);//list of user ids I want to select.
$query = sprintf("SELECT * FROM users WHERE user_id=?????", ????);
How do I do this?
$ids = implode(',',$list_of_ids);
$query = sprintf("SELECT * FROM users where user_id in ($ids)");
Convert array in comma separated string like this:
$list_of_ids = array(1, 5, 7, 23);
$out = implode(",", $list_of_ids) ;
$query = sprintf("SELECT * FROM users WHERE user_id in =(".$out.")");

How do i select multiple rows which match the value of an item in an array?

I have written a php script that returns an arbitrary number of specific ids (which are in the format of numbers) in an array. I would like to make a new query that selects each row from a table that belongs to each id. I know i can do 1 query to get one row with the matching id. But i would like to do this all in one query. Here is my code:
$id = array(1,4,7,3,11,120); // The array containing the ids
$query = mysql_query("SELECT *
FROM posts
WHERE id = '$id[0]'");
// I would like to Do this for each id in the array and return it as one group of rows.`
I think you want the IN clause:
$idList = implode(",", $id);
SELECT *
FROM posts
WHERE id IN ( $idList );
The implode() function will turn your array of numbers into a comma-separated string of those same values. When you use it as part of an IN clause, it tells the database to use those values as a lookup table to match id against.
Standard Disclaimer/Warning:
As with any SQL query, you really shouldn't be directly concatenating variables into the query string. You're just opening yourself up to SQL injection. Use prepared/parameterized statements instead.
Use PHP's implode function to convert the array into a comma separated value string.
Then, you can use the SQL IN clause to run a single SQL statement containing the values associated with the ids you captured from PHP:
$id = array(1,4,7,3,11,120);
$csv = implode(',', $id);
$query = sprintf("SELECT *
FROM posts
WHERE id IN (%s)",
mysql_real_escape_string($csv));
$result = mysql_query($query)
I omitted the single quotes because they aren't necessary when dealing with numeric values in SQL. If the id values were strings, each would have to be encapsulated inside of single quotes.
What you want is SQL's IN clause.
SELECT * FROM posts WHERE id IN (1, 4, 7, 11, 120)
In PHP, you'll probably want something like:
$query = mysql_query(sprintf("SELECT * FROM posts WHERE id IN (%s)", implode(',', $id)));
Obviously, that's assuming you know you have integer values for $id, and that the values for $id didn't come from the user (that is, they should be sanitized). To be safe, you really ought to do something like:
$ids = implode(',', array_map('mysql_real_escape_string', $id));
$query = mysql_query("SELECT * FROM posts WHERE id IN ($ids)");
And if $id is dynamically generated, don't forget to put something in that IN clause, because SELECT * FROM foo WHERE bar IN () will give you an error. I generally make sure to set my IN-clause variables to 0, since IN (0) is good, and primary keys are pretty much never 0.

Categories