If I have an array of say, some ID's of users. How could i do something like this:
$array = array(1,40,20,55,29,48);
$sql = "SELECT * FROM `myTable` WHERE `myField`='$array'";
Is there a simple way to do this, I thought about looping through array items and then building up one big "WHERE -- OR -- OR -- OR" statement but i thought that might be a bit slow for large arrays.
Use IN:
$sql = "SELECT * FROM `myTable` WHERE `myField` IN (1,40,20,55,29,48)";
you can use implode(",", $array) to get the list together from the array.
You want to use IN:
WHERE `myfield` IN (1,40,20,55,29,48)
Use implode to construct the string:
$sql = "SELECT * FROM `myTable` WHERE `myField` IN (" . implode(',', $array) . ")";
Related
I have a basic query as follows
$query = "SELECT * FROM files WHERE (subject_code = '".$subject_code."' )";
I have to modify this query to create a query where we have multiple subject codes fetched from an array.
$query1="SELECT subject_code FROM subject WHERE (sbranch = '".$branch."' )";
$result = mysqli_query($bmysqli, $query1);
Now result holds all the required subject_codes say result[0]=SC1,result[1]=SC2 etc....
Now I want to the original query to be modified something as follows
$query = "SELECT * FROM files WHERE (subject_code = SC1 OR subject_code = SC2 .....)";
Note that i don't know what are the values of SC1 SC2 etc.It depends on the branch and is inside $result.
How can i accomplish this?
You can use a subquery like this:
$query = 'SELECT * FROM files
WHERE subject_code IN (
SELECT subject_code FROM subject WHERE sbranch = "' . $branch . '"
)';
You can use implode to convert array to string comma delimited
like below:
$branch_array = array('subject1', 'subject2', 'subject3');
$branch = implode("','", $subject_array );
$query1="SELECT subject_code FROM subject WHERE sbranch in ('".$branch."')";
result:
'subject1', 'subject2', 'subject3'
Hope that resolve your issue
You can use Mysql In operator
Like this
SELECT * FROM files WHERE subject_code in ('SC1','SC2')";
You can achieve ('SC1','SC2') by using implode php function,
like this:
$subCodes = implode("','", $subject_array );
SELECT * FROM files WHERE subject_code in ('".$subCodes ."')"
$query1="SELECT subject_code FROM subject WHERE (sbranch = '".$branch."' )";
$result = mysqli_query($bmysqli, $query1);
$codes=(array)$result; //this will convert it in normal array. old school typecasting ;)
$codes=array_values($codes);
$query = "SELECT * FROM files WHERE subject_code in (".implode(",",$codes).")";
//considering result is an object of subject codes.
CODE UPDATED ABOVE as it is an object.
You don't need to append to the first query. Just build a new query using MySQL in operator and php implode function.
SELECT * FROM files WHERE subject_code in ('SC1','SC2')
You can amend your php array to comma delimited string of SubjectCodes.
then:
$query1="SELECT * FROM files WHERE subject_code in (".$NewString.") ";
$NewString will look something like this:
"'SC1', 'SC2', 'SC3'"
$result = array(0=>'SC1',1=>'SC2'); //this is your array
$branch = implode("','", $result );
$query .= "
SELECT * FROM files WHERE subject_code in ('".$branch."') "; //this is query
I try to use a php array in a postgres select statement.
I tried:
$sql = "SELECT * FROM some_table WHERE string_field IN ($1) AND other_field = $2;";
$result = pg_query_params($conn, $sql, array(implode(',', $my_arr), $other_field));
But when i run it nothing returns. (when I hardtype everything in postgres, something will be returned)
Strings needs single quotes as I know. Concat the elements of array like this:
$data = ['a','b','c','d'];
$x = "'" . implode("','", $data) . "'";
var_dump($x);
Result:
'a','b','c','d'
I have a problem in add value in SELECT query.
$sql=("SELECT `image` FROM `testtable`");
The output: 123.jpg
But I want output: 127.0.0.1/home/galery/123.jpg
So I tried:
$path='127.0.0.1/home/galery/';
.........
$sql=("SELECT $path+`image` FROM `testtable`");
But it's not working.
There are two ways to accomplish this.
Method 1:
Use string concatenation to join the path to the result from the SQL:
$path = '127.0.0.1/home/galery/';
$sql = "SELECT `image` FROM `testtable`";
// Run the query...
$result = $path . $sql;
In php, string concatenation is performed with the . operator. Also see here.
Method 2:
The second method is via the CONCAT SQL function:
$sql = "SELECT CONCAT('" . $path . "', `image`) FROM `testtable`";
Or:
$sql = "SELECT CONCAT('{$path}', `image`) FROM `testtable`";
See this question for the difference between these options.
$sql=("SELECT CONCAT('$path',`image`) FROM `testtable`");
Use concatenation like below....
$sql=("SELECT".$path."+image FROM test")
Here, text in double quotes are string
I have an array of ID:s, and the ID:s are in this format:
Bmw_330ci_89492822
So it's a string!
Now, I have this code to find whatever is in that array, in MySQL:
($solr_id_arr is the array I mentioned above, it contains string ID:s)
ex: $solr_id_arr[0] outputs Bmw_330ci_89492822
$solr_id_arr_imploded = implode(", ", $solr_id_arr);
$query = "SELECT * FROM my_table WHERE ad_id IN ('$solr_id_arr_imploded')";
$qry_result = mysql_query($query) or die(mysql_error());
Problem is this wont work because (I think) that there should be quotes around each of the imploded elements in order for MySQL to find the match. The field in MySQL I am matching is of type Varchar.
Here is the $query echoed:
SELECT * FROM my_table WHERE ad_id IN ('Bmw_m3_cool_565440282, Bmw_m5_839493889')
Do you have any other solutions for this, all I need is to find matches in MySQL which are inside this array!
Thanks
Don't surround the entire thing in quotes. It is looking for where ad_id is 'Bmw_m3_cool_565440282, test'
Use
SELECT * FROM my_table WHERE ad_id IN ('Bmw_m3_cool_565440282', 'test')
A quick fix would be to change:
//this
$solr_id_arr_imploded = implode(", ", $solr_id_arr);
//to this
$solr_id_arr_imploded = implode("', '", $solr_id_arr);
This one seems complicated but it's more safer and fastest one
function escaped($str)
{
return mysql_escape_string($str);
}
$arrayOfIds = array_map("escaped", $solr_id_arr);
$solr_id_arr_imploded = implode(", ", $arrayOfIds);
$query = "SELECT * FROM my_table WHERE ad_id IN ('$solr_id_arr_imploded')";
$qry_result = mysql_query($query) or die(mysql_error());
Simple switch to ', ' in implode():
implode("', '", $solr_id_arr);
This, together with the hardcoded quotes in the SQL string will format them as separate items.
Previous answers will work fine.
Just make sure the strings themselves do not contain quotes. If they do, escape each string before you do the implode().
If it were my code I'd write it like this:
$solr_id_arr_imploded = "'" . implode("', '", $solr_id_arr) . "'";
$query = "SELECT * FROM my_table WHERE ad_id IN ($solr_id_arr_imploded)";
$qry_result = mysql_query($query) or die(mysql_error());
...just because it keeps all the quoting work in one place. You might also want to make sure that the array isn't empty before entering this block of code. Otherwise the SELECT will match all empty ad_id's, which probably isn't what you wanted. We're also assuming that the elements of the array don't include any quote characters (or user-provided strings that haven't been sanity-checked).
I'm trying to build a query using php and mysql,
$query = "select * from products where product_name = '$item_name'";
this works when $item_name holds only one name, but $item_name is an array and based on the user's interaction can contain multiple names, how can I make the query to run for multiple name and get the resulted rows.
Thanks in advance
Here's how you could build a safe list of names for inserting into an IN clause...
if (is_array($names) && count($names))
{
$filter="('".implode("','" array_map('mysql_real_escape_string', $names))."')";
$sql="select * from products where product_name in $filter";
//go fetch the results
}
else
{
//input was empty or not an array - you might want to throw an
//an error, or show 'no results'
}
array_map returns the input array of names after running each name through mysql_real_escape_string to sanitize it. We implode that array to make a nice list to use with an IN clause.
You should always ensure any data, particularly coming directly from the client side, is properly escaped in a query to prevent SQL injection attacks.
$vals = implode(',',$item_name);
$query = "select * from products where product_name in (".$vals.");";
Give that a try.
$query = "select * from products where product_name in(";
foreach($item_name as $name)
{
$query .= "'" . $item_name . "', ";
}
$query = substr($query, 0, strlen$query) - 2);
$query .= ");";
First answer (by inkedmn) is really the best one though
foreach($item_name as $name) {
$query = "select * from products where product_name = '$name'";
//whatever you want to do with the query here
}
something like that ought to do it.
Based on inkedmn's response (which didn't quote the item names):
$query = 'select * from products where product_name in ("' . implode('", "', $item_name ) . '")';
Although you may be better with a fulltext search.
http://dev.mysql.com/doc/refman/5.1/en/fulltext-search.html