This question already has answers here:
Passing an array to a query using a WHERE clause
(17 answers)
Closed 8 years ago.
i have a problem making a SQL Query with an array in my WHERE clause.
For example:
My Array:
$myarray[1] = "hi";
$myarray[2] = "there";
$myarray[3] = "everybody";
My MySQL Statement:
SELECT * FROM myTable WHERE title='".$myarray[]."'
Is there any way to realize that?
I solved it myself like this:
for(...) {
$where = $where." title='".$myarray[$count]."' OR ";
}
$where = substr($where , 0, -3);
.....
SELECT * FROM myTable WHERE ".$where."
But if i had thousands of entries in my array, the SQL Statement would be too big and slow, right?
Thanks
You can use mysql's IN-function
EDIT: As amosrevira said, you need to escape you strings in the array.
$myarray[1] = "'hi'";
$myarray[2] = "'there'";
$myarray[3] = "'everybody'";
$newarray = implode(", ", $myarray); //makes format 'hi', 'there', 'everybody'
SELECT * FROM myTable WHERE title IN ($newarray);
$myarray[1] = "hi";
$myarray[2] = "there";
$myarray[3] = "everybody";
//every quoted string should be escaped according to SQL rules
foreach($myarray as $key => $val) {
$myarray[$key] = mysql_real_escape_string($val);
}
$in_str = "'".implode("', '", $myarray)."'"; //makes format 'hi', 'there', 'everybody'
SELECT * FROM myTable WHERE title IN ($in_str);
You can try use of IN in your WHERE clause,
SELECT * FROM myTable WHERE title IN ('hi', 'there', 'everybody');
or
SELECT * FROM myTable WHERE title IN ('.implode(',', $myarray).');
You can us the IN operator. You want it to look like:
title IN ('hi', 'there', 'everybody')
So you'd do something like:
$sql = "SELECT * FROM myTable WHERE title IN '" . implode("','", $myarray) . "';"
Note that you need to filter your array for SQL injection issues first.
Related
I got an array of ids that I want to use inside an IN statement (sql). However this can only be done when it is written correctly, for example: IN ('12', '13', '14')
How can I change an array of ids into that format? This means adding quotes around every number, and after every number surrounded by quotes a comma, except for the last one in the array.
My code:
$parent = "SELECT * FROM `web_categories` WHERE `parent_id` = 13 AND published = 1";
$parentcon = $conn->query($parent);
$parentcr = array();
while ($parentcr[] = $parentcon->fetch_array());
foreach($parentcr as $parentid){
if($parentid['id'] != ''){
$parentoverzicht .= "".$parentid['id']."";
}
}
I later want to use it like this:
$project = "SELECT * FROM `web_content` WHERE `catid` IN ('".$parentoverzicht."') AND state = 1";
Do this as a single query! SQL engines have all sorts of optimizations for working with tables, and doing the looping in your code is usually way more expensive.
The obvious query for your purposes would be:
SELECT wc.*
FROM web_content wc
WHERE wc.catid IN (SELECT cat.id
FROM web_categories cat
WHERE cat.parent_id = 13 AND cat.published = 1
) AND
wc.state = 1;
Use implode()..
<?php
$a1 = array("1","2","3");
$a2 = array("a");
$a3 = array();
echo "a1 is: '".implode("','",$a1)."'<br>";
echo "a2 is: '".implode("','",$a2)."'<br>";
echo "a3 is: '".implode("','",$a3)."'<br>";
?>
output->>>>>>>
a1 is: '1','2','3'
a2 is: 'a'
a3 is: ''
Have you tried to implode()?
Use ", " as glue. You will have to edit the string yourself to add a " at the beginning and end.
More info: http://php.net/manual/en/function.implode.php
Alternatively you can use single join query, like this.
SELECT con.* FROM `web_content` as con LEFT JOIN `web_categories` as cat
ON con.catid=cat.id WHERE cat.parent_id=13 AND published = 1
If the column's type in the DB is integer you do not actually need to quote the values, but in case it isn't, you can use array_map to quote every item in the array, then implode to join them with commas:
<?php
$ids = [1, 2, 3, 4, 5];
$sql = 'SELECT * FROM mytable WHERE id IN (?)';
$in_clause = array_map(function ($key) {
return "'$key'";
}, $ids);
$sql = str_replace('?', implode(',', $in_clause), $sql);
echo $sql;
Result:
SELECT * from mytable where id in ('1','2','3','4','5')
You can do something like this:
$ids = ['1','2','3','4']; //array of id's
$newArr = array(); //empty array..
foreach($ids as $ids)
{
$newArr[] = "'".$ids."'"; //push id into new array after adding single qoutes
}
$project = "SELECT * FROM `web_content` WHERE `catid` IN (".implode(',',$newArr).") AND state = 1"; /// implode new array with commaa.
echo $project;
This will give you :
SELECT * FROM `web_content` WHERE `catid` IN ('1','2','3','4') AND state = 1
This question already has answers here:
Can I bind an array to an IN() condition in a PDO query?
(23 answers)
Closed 1 year ago.
I stored some data in a field inside MySQL in this format: 1,5,9,4
I named this field related. Now I want to use this field inside an IN clause with PDO. I stored that field contents in $related variabe. This is my next codes:
$sql = "SELECT id,title,pic1 FROM tbl_products WHERE id IN (?) LIMIT 4";
$q = $db->prepare($sql);
$q->execute(array($related));
echo $q->rowCount();
But after executing this code, I can fetch only one record whereas I have to fetch 4 records (1,5,9,4). What did I do wrong?
using named place holders
$values = array(":val1"=>"value1", ":val2"=>"value2", ":val2"=>"value3");
$statement = 'SELECT * FROM <table> WHERE `column` in(:'.implode(', :',array_keys($values)).')';
using ??
$values = array("value1", "value2", "value3");
$statement = 'SELECT * FROM <table> WHERE `column` in('.trim(str_repeat(', ?', count($values)), ', ').')';
You need as many ? placeholders as your "IN" values.
So:
$related = array(1,2,3); // your "IN" values
$sql = "SELECT id,title,pic1 FROM tbl_products WHERE id IN (";
$questionmarks = "";
for($i=0;$i<count($related);$i++)
{
$questionmarks .= "?,";
}
$sql .= trim($questionmarks,",");
$sql .= ") LIMIT 3;";
// echo $sql; // outputs: SELECT id,title,pic1 FROM tbl_products WHERE id IN (?,?,?) LIMIT 3;
$q = $db->prepare($sql);
$q->execute($related); // edited this line no need to array($related), since $related is already an array
echo $q->rowCount();
https://3v4l.org/No4h1
(also if you want 4 records returned get rid of the LIMIT 3)
More elegantly you can use str_repeat to append your placeholders like this:
$related = array(1,2,3); // your "IN" values
$sql = "SELECT id,title,pic1 FROM tbl_products WHERE id IN (";
$sql .= trim(str_repeat("?,",count($related)),",");
$sql .= ") LIMIT 3;";
// echo $sql; // outputs: SELECT id,title,pic1 FROM tbl_products WHERE id IN (?,?,?) LIMIT 3;
$q = $db->prepare($sql);
$q->execute($related); // edited this line no need to array($related), since $related is already an array
echo $q->rowCount();
https://3v4l.org/qot2k
Also, by reading again your question i can guess that your $related variable is just a string with value comma-separated numbers like 1,40,6,99. If that's the case you need to make it an array. do: $related = explode($related,","); to make it an array of numbers. Then in your execute method pass $related as-is.
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, ',') . ")";
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);
I am creating a PHP function that will take some values, one of which is an array, that I need to use in a MySQL query.
I am creating the array as follows:
$newsArray = createArticleArray(array(2,20,3),5);
Then the function looks something like this (cut down for readability)
function createArticleArray($sectionArray = array(1),$itemsToShow)
{
$SQL = "
SELECT
*
FROM
tbl_section
WHERE
(tbl_section.fld_section_uid = 2 OR tbl_section.fld_section_uid = 20 OR tbl_section.fld_section_uid = 3)
ORDER BY
tbl_article.fld_date_created DESC LIMIT 0,$itemsToShow";
}
The section tbl_section.fld_section_uid = 2 OR tbl_section.fld_section_uid = 20 OR tbl_section.fld_section_uid = 3 is where I need to use the array values.
Basically I need to loop through the values in the array making up that part of the query, however I am having a little problem on how to show or not show the "OR" bits of it as there might be only 1 value or as many as I need.
I was thinking of something like this:
foreach($sectionArray as $section)
{
$sqlString = $sqlString . "tbl_section.fld_section_uid = $section OR";
}
but I don't know how to work out if to put the "OR" in there.
Use implode.
$conditionParts = array();
foreach($sectionArray as $section){
$conditionParts[] = "tbl_section.fld_section_uid = $section";
}
$sqlString .= implode(' OR ', $conditionParts);
This solution answers your question and show you how to use the implode function, but for your specific case you should really use the IN operator.
$sqlString .= "tbl_section.fld_section_uid IN(".implode(',', $sectionArray).")";
One solution is to put an extraneous 0 at the end to consume the final "OR" without any effect. The query parser will just remove it: A OR B OR C OR 0 is turned into A OR B OR C.
Another solution is to use implode to insert the OR:
$sqlString = "tbl_section.fld_section = "
. implode($sectionArray," OR tbl_section.fld_section_uid = ");
Of course, the correct solution is just to use IN:
"WHERE tbl_section.fld_section_uid IN(".implode($sectionArray,',').")";
The query can be made simpler and easier to generate if you use WHERE <column> IN (value1,value2,...) syntax.
Use PHP's implode to produce the (value1,value2,...) part:
$SQL .= ' WHERE tbl_section.fld_section_uid IN (' . implode(',', $array) . ') ';
Yields something like this:
SELECT
...
WHERE tbl_section.fld_section_uid IN (2,20,3)
...
Use PDO's prepare method: http://uk3.php.net/manual/en/pdo.prepare.php
$statement = $pdo->prepare("
SELECT
*
FROM
tbl_section
WHERE
(tbl_section.fld_section_uid = ? OR tbl_section.fld_section_uid = ? OR tbl_section.fld_section_uid = ?)
ORDER BY
tbl_article.fld_date_created DESC LIMIT 0,$itemsToShow");
$statement->execute( $sectionArray );
function createArticleArray($sectionArray = array(), $itemsToShow) {
$conditions = array();
for ($i = 0, $s = count($sectionArray); $i < $s; ++$i) {
$conditions[] = 'tbl_section.fld_section_uid = ' . (int) $sectionArray[$i];
}
$SQL = 'SELECT * FROM tbl_section WHERE ' . implode(' OR ', $conditions) . ' ORDER BY tbl_article.fld_date_created DESC LIMIT 0, ' . (int) $itemsToShow;
}