How to query a database with an array? WHERE = 'array()' - php

I'm wondering how to query a database using an array, like so:
$query = mysql_query("SELECT * FROM status_updates WHERE member_id = '$friends['member_id']'");
$friends is an array which contains the member's ID. I am trying to query the database and show all results where member_id is equal to one of the member's ID in the $friends array.
Is there a way to do something like WHERE = $friends[member_id] or would I have to convert the array into a string and build the query like so:
$query = "";
foreach($friends as $friend){
$query .= 'OR member_id = '.$friend[id.' ';
}
$query = mysql_query("SELECT * FROM status_updates WHERE member_id = '1' $query");
Any help would be greatly appreciated, thanks!

You want IN.
SELECT * FROM status_updates WHERE member_id IN ('1', '2', '3');
So the code changes to:
$query = mysql_query("SELECT * FROM status_updates WHERE member_id IN ('" . implode("','", $friends) . "')");
Depending on where the data in the friends array comes from you many want to pass each value through mysql_real_escape_string() to make sure there are no SQL injections.

Use the SQL IN operator like so:
// Prepare comma separated list of ids (you could use implode for a simpler array)
$instr = '';
foreach($friends as $friend){
$instr .= $friend['member_id'].',';
}
$instr = rtrim($instr, ','); // remove trailing comma
// Use the comma separated list in the query using the IN () operator
$query = mysql_query("SELECT * FROM status_updates WHERE member_id IN ($instr)");

$query = "SELECT * FROM status_updates WHERE ";
for($i = 0 ; $i < sizeof($friends); $i++){
$query .= "member_id = '".$friends[$i]."' OR ";
}
substr($query, -3);
$result = mysql_query($query);

Related

how to search multiple username in a single query

I want to search for some username in my database like this->
$skip = $_POST['username'];
$_SESSION['skip_user'] = array();
array_push($_SESSION['skip_user'],$skip);
$str = $_SESSION['skip_user'];
$string = rtrim(implode(',', $str), ',');
Now string variable looks like "name1, name2, name3";
mysqli_query($db, "SELECT * FROM users WHERE username in ({$string}) ORDER BY id DESC");
This fetches the users but i don't want these users. I mean is there any query where i can i write WHERE username !in ({$string})!
get all users except "name1, name2, name3" these users
Now after adding NOT IN I'm receiving error
mysqli_query($db, "SELECT * FROM users WHERE username NOT IN ({$string}) ORDER BY id DESC")or die(mysqli_error($db)); php is giving error Unknown column 'name1' in 'where clause'
Try NOT IN in the SQL query.
First though try to add quotes to the values you are trying in the NOT IN part of the sql query.
$str = '';
foreach ($_SESSION['skip_user'] AS $word) {
$str .= "'$word',";
}
$str = rtrim($str, ',');
Then use this $str in your query. Also, try to make a habit out of using `` for column names, like this:
SELECT `SOMETHING` FROM `TABLE_NAME` WHERE <CONDITION>
I hope that helps!
You should use NOT IN to exclude certain values.
mysqli_query($db, "SELECT * FROM users WHERE username NOT IN ('name1', 'name2') ORDER BY id DESC");
yep, just type "not" instead of "!"
select * from table where junk not in ('item1', 'item2', 'item3');
1) You have a few other problems though you're not adding quotes to your implode:
// you need quotes here
$string = implode("','", $str);
// And here
mysqli_query($db, "SELECT * FROM users WHERE username in ('{$string}') ORDER BY id DESC");
However, this is what you should really be doing.
2) You should bind your parameters instead as you're open to SQL injection:
$params = array();
$params[0] = "";
$sql = "SELECT * FROM users WHERE username NOT IN (";
foreach($str as $s){
$params[0] .= "s";
array_push($params, $s);
$sql .= "?, ";
}
$sql = rtrim($sql, " ,").") ORDER BY id DESC";
$stmt = $conn->prepare($sql);
// this is the same as doing: $stmt->bind_param('s', $param);
call_user_func_array(array($stmt, 'bind_param'), $params);
// execute and get results
$stmt->execute();

Create MySQL query with IDs from results

I have a a form which let's the user select what they want to display. Now the results of this looks like that: 9, 10, 11. These are IDs from the table.
These are the IDs of the type they what to show. I have my query already, but I want to add this part at the end of my query.
So in this case:
$query = "type_ID = $result1 or type_ID = $result2 or type_ID = $result3"
if printed out with echo:
type_ID = 9 or type_ID = 10 or type_ID = 11
How can I achieve this?
I tried to loop and it,however this did not work and I am confused how to do add the MySQL code to this.
$result = $result . $_GET['type_ID'][$i]
I'm a tad unsure of what it is you are trying to achieve but from what I understand this should do it:
<?php
$tID = $_GET['type_ID'];
$query = 'SELECT * FROM table WHERE';
$i = 0;
foreach($tID AS $id){
if($i == 0){
$query .= ' type_ID = ' . $id;
$i++;
}else{
$query .= ' OR type_ID = ' . $id;
}
}
Although if you are only looking for the type_ID I'd still recommend using IN() like so:
<?php
$tID = $_GET['type_ID'];
$query = "SELECT * FROM table WHERE type_ID IN (" . implode(',',$tID) . ")";
In works just like OR, just instead of having to write multiple OR you can just use a single IN() :)
Have you try this ?
$sql = "SELECT * FROM table WHERE ".$query;

Pass an array as parameters to SQL procedure

I have SQL procedure in which I'm using an IN statment. It goes like this:
SELECT * FROM costumers WHERE id IN('1','2','12','14')
What I need to do is pass the values in to the IN statment as parameter which is an array in php, rather than hard-coded. How can I do that?
You can implode on this case:
$array = array('1','2','12','14');
$ids = "'".implode("','", $array) . "'";
$sql = "SELECT * FROM `costumers` WHERE `id` IN($ids)";
echo $sql;
// SELECT * FROM `costumers` WHERE `id` IN('1','2','12','14')
or if you do not want any quotes:
$ids = implode(",", $array);
You can use PHP function Implode
$array = array("1","2","12","14");
$query = "SELECT * FROM costumers WHERE id IN(".implode(', ',$array).")"
implode() is the right function, but you also must pay attention to the type of the data.
If the field is numeric, it is simple:
$values = array(1. 2, 5);
$queryPattern = 'SELECT * FROM costumers WHERE id IN(%s)';
$query = sprintf($queryPattern, implode(', ',$values));
But if it's a string, you must play with single and double quotes:
$values = array("foo","bar","baz");
$queryPattern = 'SELECT * FROM costumers WHERE id IN("%s")';
$query = sprintf($queryPattern, implode('", "',$values));
This should do the trick
$array = array('1','2','12','14');
SELECT * FROM `costumers` WHERE `id` IN('{$array}');
Try imploding the php into an array, and then interpolating that string into the SQL statement:
$arr = array('foo', 'bar', 'baz');
$string = implode(", ", $arr);
SELECT * FROM customers WHERE id in ($string);
use PHP's join function to join the values of an array.
$arr = array(1,2,12,14);
$sql = "SELECT * FROM costumers WHERE id IN(" . join($arr, ',') . ")";

passing array of values in sql select statement of where condition

$sql = "select id from table_name ";
$result = mysql_query($sql);
$data = array();
while($row = mysql_fetch_assoc($result))
{
$data[] = $row[id];
}
/* $data contains id's fetched from sql query from db.now i want to pass this id's(array of values) in $data array one by one to below select query in where condition and obtain desired result for each id.My question is how to pass an array of values to the below select statement I dont know how to do this.Any help is greatly appreciated.*/
$query = "select * from table where id1 = $data[] ";
$query = "select * from table where `id1` in (" . implode(', ', $data) . ")";
You should use the cross database function in Moodle called get_in_or_equal()
list($where, $params) = $DB->get_in_or_equal($data, SQL_PARAMS_NAMED);
$sql = "SELECT *
FROM {table}
WHERE $id {$where}"
$records = $DB->get_records_sql($sql, $params);
You can use the IN clause.
When you are totally sure you only have numeric values in your $data array. You can do the following:
$query = "select * from table where id1 IN(" . implode(',', $data) . ")";
You can use this:
$comma_separated = implode(",", $data);
if ($comma_separated != "")
$query = "select * from table where id1 IN($comma_separated)";

How to correctly parse an array for an SQL query

When you need to do something like this:
SELECT * FROM userinfo WHERE id in (18,2,6,4,5)
And the id array comes from another query like:
$ids = $conn->fetchAll('SELECT origin from action WHERE url = "'.$url.'" AND SUBSTRING(origin,1,3)<>"pct" GROUP BY origin');
If I need to parse the array in order to give the right format to the query id do:
$norm_ids = '(';
foreach ($ids as $ids) {
$norm_ids .= $ids['origin'] .',';
}
$norm_ids = substr_replace($norm_ids ,"",-1) .')';
That outputs the ids like: (id1,id2,id3,id.......), so the I'll just: FROM userinfo WHERE id in ". $norm_ids;
But seems to ugly to me, is there a way to do this better?
You could do:
$idStr = rtrim(str_repeat('?,', count($ids), ',');
$query = 'SELECT * FROM userinfo WHERE id in (' . $idStr . ')';
and then use prepare():
$conn = $db->prepare($query);
$conn->execute($ids);
$res = $conn->fetchAll(...);
SELECT * FROM user_info WHERE id IN (SELECT origin from action ......) ....
Do you need the id's separate or can you combine them into 1 query?
perhaps something like:
SELECT * FROM userinfo WHERE id in (SELECT origin from action WHERE url = "'.$url.'" AND SUBSTRING(origin,1,3)<>"pct" GROUP BY origin');
this way you let the sql server do the work.
When i am faced with such situations, i use trim
$norm_ids_str = '';
foreach ($ids as $ids) {
$norm_ids_str .= $ids['origin'] .',';
}
$norm_ids = '(' . trim($norm_ids_str, ',') . ')';

Categories