How to use PHP array in Postgres select - php

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'

Related

How to create a query dynamically for an array of elements?

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

Error in PHP & MySQL query

I'm trying to make query with a variable which represents the users.
This is the query:
$sq12 = "select sum(monto) from pagos where usuario = $_SESSION['XUSUARIO']" or die(mysql_error());
$re2 = mysql_query($sq12,$conexion);
$_SESSION['XUSUARIO'] is the data of each user to lookup in the db.
Edit:
I changed the query as requested, now it says ARRAY.
or die() is in the wrong place.
$sq12 ="select sum(monto) from pagos where usuario = {$_SESSION['XUSUARIO']}";
$re2 = mysql_query($sq12,$conexion) or die(mysql_error());
You can only interpolate scalar values into a string. To use an array of ids for example, use implode (or the alias join):
<?php
$usuario = implode(',',$_SESSION['XUSUARIO']);
$sq12 = "select sum(monto) from pagos where usuario in ($usuario)";
$re2 = mysql_query($sq12,$conexion) or die(mysql_error());
EDIT: PDO PDO PDO PDO
$_SESSION['XUSUARIO'] is an array, you will need to format it into a string for the query, doing something like this:
$string = '(';
$string .= implode(',', $_SESSION['XUSUARIO']);
$string .= ')';
And then add it into the query:
"... where usuario IN $string"

PHP + MySQL "WHERE ... IN" doesn't work

I build my query like this:
foreach($ids as $key => $idi) {
$ids[$key] = "'" . $idi . "'";
};
$ids_imploded = implode(", ", $ids);
$sql = "SELECT record_id, email FROM `actions_attendees` WHERE `action_id` IN (" . $ids_imploded . ") AND `backup` = 1 ORDER BY `timestamp` ASC LIMIT " . count($ids) . ";";
$result = mysqli_query($con, $sql);
Where $ids is just array of few numbers (so the $ids_imploded = "'132', '165'").
When I run the generated query in phpMyAdmin, I get what I want. When I run it from PHP, it returns just object with nulls. Why?
I doesn't work neither if I remove the escaping loop.
EDIT: generated query is echoed like
SELECT record_id, email FROM `actions_attendees` WHERE `action_id` IN ('1614', '1615') AND `backup` = 1 ORDER BY `timestamp` ASC LIMIT 2;
The problem could be that you are querying the wrong database, try select a db first, try executing this before the query :
mysql_select_db('yourdb');
Is the result of your query true ? Check your connection object, it seems like you are not on the right database.
It appears that the query was indeed working even in PHP, but later when I was processing the results, intellisense tricked me and I was using mysql_fetch_assoc instead of mysqli_fetch_assoc...

Select from mysql table WHERE field='$array'?

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) . ")";

Small Php and MySql problem

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).

Categories