using where statement with a sequence of ids - php

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.

Related

Select statement with where clause Like in array

I know how to perform an SQL LIKE % query for a single value like so:
$sql = "SELECT * FROM Farmers WHERE Available_products LIKE ('%Bananas%')";
but how do I do this if the search terms for my LIKE comes from an array? For example, let's say we have an array like this:
$_POST['Products']="Cacaos,Bananas";
$array=implode(',', $_POST['Products']);
$sql = "SELECT * FROM Farmers WHERE Available_products LIKE ('%$array%')";
I want to get all the records in database that the column Available_Products contains Cacaos or Bananas or Both
Convert the array to a regular expression and use REGEX instead of LIKE
$_POST['Products'] = array('Cacaos', 'Bananas');
$regex = implode('|', $_POST['Products']);
$sql = "SELECT * FROM Farmers WHERE Available_products REGEX :regex";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':regex', $regex);
$stmt->execute();
You can try with the help of REGEXP .
$_POST['Products']="Cacaos,Bananas";
$array=implode('|', $_POST['Products']);
$sql = "SELECT * FROM Farmers WHERE
Available_products REGEXP". $array; 
You can also do something like :
// Populating join table.
CREATE TABLE temp_table_myArray (myArray nvarchar(255));
INSERT INTO temp_table_myArray (myArray) VALUES ('Cacaos');
INSERT INTO temp_table_myArray (myArray) VALUES ('Bananas');
// Query using the join table.
SELECT F.*
FROM Farmers AS F
INNER JOIN temp_table_myArray AS T ON (F.Available_products LIKE(CONCAT('%',T.myArray,'%')));
But I think there is a better PHP way to solve your 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

PHP PDO result from query

I am trying to do a query in PHP PDO where it will grab a simple result. So like in my query I need it to find the row where the column group is 'Admin' and show what ever is in the group column. I know that we already know what it should be [Should be admin] but just need to get the query to work. Its only grabbing 1 row from my table, so will I need forsearch?
If I change WHERE group = 'Admin' to WHERE id = '1' it works fine. But I need it so it can be where group = 'admin'
$sql2 = "SELECT * FROM groups WHERE group = 'Admin'";
$stm2 = $dbh->prepare($sql2);
$stm2->execute();
$users2 = $stm2->fetchAll();
foreach ($users2 as $row2) {
print ' '. $row2["group"] .' ';
}
Thanks
group is a reserved word in MySQL, that's why it's not working. In general it's a bad idea to use reserved words for your column and table names.
Try using backticks around group in your query to get around this, so:
$sql2 = "SELECT * FROM groups WHERE `group` = 'Admin'";
Also you should really use placeholders for values, because you're already using prepared statement it's a small change.
Edit: just to clarify my last remark about the placeholders. I mean something like this:
$sql2 = "SELECT * FROM groups WHERE `group` = ?";
$stm2->execute(array('Admin'));
try to use wildcard in your WHERE Clause:
$sql2 = "SELECT * FROM groups WHERE group LIKE '%Admin%'";
Since the value in your table is not really Admin but Administrator then using LIKE and wildcard would search the records which contains admin.

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

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