how to pass json array to select query - php

I have json array as below
$q=[{"con0":0},{"con1":1},{"con2":2}]
I want to pass this array to select query where query is as follows
$query="select * from table_name where con0='0' and con1='1' and con2='2'";
Shall we use json array to create this query?

The two tricks are to turn the json into a php array via json_decode and then use reset() and key() functions to get the column and condition. Here is the live example:
http://ideone.com/wp1kb1 you can read more about key http://php.net/key and reset http://php.net/reset
<?php
$q='[{"con0":0},{"con1":1},{"con2":2}]';
$ar = json_decode($q, true);
$where = array();
foreach ($ar as $condition) {
$value = reset($condition);
$column = key($condition);
$where[] = " `$column` = " . (int) $value;
}
$whereString = implode(' AND', $where);
$query="select * from table_name where $whereString";
echo "\n $query \n";

Use json_decode to make this an object/array and then use a loop to make a string for that and append to the sql query.

Loop the JSON decoded data inside a foreach, then grab the key-value pair , store them in an array and after the end of the loop, do an implode() on the array with AND and now pass the string to your query as shown.
$json='[{"con0":0},{"con1":1},{"con2":2}]';
$qstr=array();
foreach(json_decode($json,true) as $k=>$arr)
{
$qstr[]="`".key($arr)."`"." = ".$arr[key($arr)];
}
$qstr = implode(' AND ',$qstr); //looks like `con0` = 0 AND `con1` = 1 AND `con2` = 2
$query="select * from table_name where ".$qstr;

Related

How to loop mysql result inside an array

I have an array like this
$EN=array(
"text1"=>"translation1",
"text2"=>"translation2",
"text3"=>"translation3",
"text4"=>"translation4",
);
and this is my query
$result = "SELECT langVar, translation FROM lang WHERE langName = 'EN';";
$test= $conn->query($result);
The langVar column will retrieve text variables and the translation column is for translation words.
$EN=array(
foreach ($test AS $row){
$row['langVar']=>$row['$translation']
}
);
but it was a syntax error
Please, how can I do this the right way ?
You can't put a loop inside an array literal.
Add to the array inside the loop, not the other way around:
$EN = [];
foreach ($test as $row) {
$EN[$row['langVar']] = $row['translation'];
}
DEMO
You don't need a loop. If you only want to fetch all rows into a multidimensional array indexed by one of its columns, you cause use fetch_all() and array_column().
$result = "SELECT langVar, translation FROM lang WHERE langName = 'EN'";
$EN = array_column($conn->query($result)->fetch_all(), 0, 1);

Passing array in where condition in sql query using php

I am trying to pass a array in sql query.
Array contains coloumn names as index they are assigned to their respective values which i got using GET method.
for example iam trying to compile this code :
$a='email';
$b=array($a => $_GET['x']);
$sql="SELECT * FROM users WHERE $b";
echo $sql;
The output that i need is:
SELECT * FROM users WHERE email='/*value of $_GET['x']*/'
the output that i am getting is:
SELECT * FROM users where Array
can some one help me how to make it work.
You need to manipulate the $b array to make it into the string your after, at the moment it's just dumping the content in it's own format.
This version will do what your after...
$b=array($a => $_GET['x']);
$columns = [];
foreach ( $b as $name => $value ) {
$columns[] = "$name = '$value'";
}
$sql="SELECT * FROM users WHERE ".implode(" and ", $columns);
echo $sql.PHP_EOL;
I've made it use and as the condition linking multiple columns, you can change this depending on your requirement.
This version instead uses bind parameters, the place holder is inserted instead of the value in the query and then you will need to bind the $data array to the prepared statement (how depends in the API your using). This is safer and more flexible (and recommended)...
$b=array($a => $_GET['x']);
$columns = [];
$data = [];
foreach ( $b as $name => $value ) {
$columns[] = "$name = ?";
$data[] = $value;
}
$sql="SELECT * FROM users WHERE ".implode(" and ", $columns);
echo $sql.PHP_EOL;

Adding arrays to a php variable

I am using PDO in order to select some values from my database.
For each iteration of my $teachArray, I store the selected array into my $language_id variable. I then get rid of any empty array that I have inside my $language_id and assigning it to my $NoEmptyArray_language_id However, I am only storing the last array inside of $language_id in $NoEmptyArray_language_id.
I would like to concatenate every array in $language_id into $NoEmptyArray_language_id.
I cannot use $NoEmptyArray_language_id .= $language_id; since it will give me an error: Array to String conversion
Here is my simple query.
$sqlFindId = "SELECT language_id
FROM language_skill
WHERE person_id = :person_id AND language_learning = :language_learning AND language_id = :language_id";
$NoEmptyArray_language_id = "";
foreach ($teachArray as $dataTeach)
{
$query = $handler->prepare($sqlFindUser);
$query->bindValue(':person_id', $_SESSION['person_id']);
$query->bindValue(':language_learning', 1);
$query->bindValue(':language_id', $dataTeach);
$query->execute();
$language_id = $query->fetchAll(PDO::FETCH_COLUMN, 0);
if ( count( $language_id ) != 0 ) {
$NoEmptyArray_language_id .= $language_id;
}
}
print_r($NoEmptyArray_language_id);
You have to define $NoEmptyArray_language_id = array();
Also change code with $NoEmptyArray_language_id[] = $language_id;
Now you have array with values in $NoEmptyArray_language_id.
If you want to get string convert this array to string using implode function.

PHP Array within array issue

I have an array like the one given below:
{
"quantity":"1",
"product_id":"41",
"option[232]":"28",
"option[231][]":"25"
}
I run the above in a foreach loop as $key => $value. But when I try to concatenate them into a string, I get an Array to String conversion error.
Eg: $result = $this->db->query("SELECT a.quantity quantity, b.name optionname FROM " . DB_PREFIX ."product_option_value a, " . DB_PREFIX ."option_value_description b WHERE a.option_value_id = b.option_value_id AND a.product_option_id=".$key." AND a.product_option_value_id=".$value." AND a.product_id=".$product_info['product_id']." AND a.subtract=1");
When I remove the last entry of "option[231][]":"25", it works fine. Is there anyway I can convert the "option[231][]" to "option[231]".
I am posting to a php page via json.
Thanks
Just use the print_r function to convert the multi-dim array, e.g.
option[231] = print_r(option[231], TRUE);
or, if you don't like the resulting syntax, nest a foreach loop within the existing foreach loop which executes when the variable is an array, e.g.
if(is_array(option[$x])){
$y = '';
foreach(option[$x] as $value){
$y .= $value;
}
option[$x] = $y;
}

Build SQL Select a better way ? (Oracle)

i have the following code part in one of my classes:
$l = new Location();
$result = $l->getLocIdsbyCity($city); // returns csv
$ids = explode(',', $result);
$where = 'LOC_ID = ' . $ids[0];
unset($ids[0]);
foreach ($ids as $id) {
$where .= ' OR LOC_ID = ' . $id;
}
$select->where($where);
Is there an more "elegant" way to build the select stmt? I need all records with one of the provided ids..
Assuming your csv is injection safe (contains trusted values and no user-provided input):
$l = new Location();
$result = $l->getLocIdsbyCity($city); // returns csv
$where = "LOC_ID IN ($result)";
$select->where($where);
If it's not, you should explode it, mysql_real_escape_string each value and implode back.
You can use the in operator to form a condition like:
where LOC_ID in (1,2,3,4,5)
If you are sure that $result can't contain anything harmful, you should be able to use it directly without having to split it and loop.

Categories