Construct SELECT WHERE query with array_keys and array_values in PHP - php

I was able to use array_keys and array_values to do an INSERT for MySQL:
$columns = implode(", ", array_keys($cmd_array));
$escaped_values = array_map( $dbc->real_escape_string, array_values($cmd_array));
$values = implode(", ", $escaped_values);
$query = "INSERT INTO cmd ($columns) VALUES ($values)";
Is there a feature to do the same thing for SELECT WHERE like this?
$query = "SELECT * FROM cmd WHERE ($columns) = ($values)";

You have to specify more than one condition using the AND or the OR operators.
So you can do this with a simple loop
$select_query = "SELECT * FROM cmd WHERE ";
$temp_array = array();
foreach($cmd_array as $key=>$val){
$temp_string = $key ." = ".$val;
array_push($temp_array, $temp_string);
}
$select_query .= implode(" AND ", $temp_array);

Related

PHP/MySQLi using a string array in WHERE IN clause with prepared statements

I want to make a dynamic WHERE clause to find posts by multiple posters. This is my code so far.
$in = join(',', array_fill(0, count($myArray), "?"));
$query = "SELECT * FROM posts WHERE poster IN ($in)";
$statement = $conn->prepare($query);
$statement->bind_param(str_repeat("s", count($myArray)), ...$myArray);
$statement->execute();
$result = $statement->get_result();
The above code is working but only for the very first person in my array. How will I be able to get the posts from every person listed in the array?
Build up a string and append it to $query using a foreach loop
$where = "where poster IN ( "
foreach ($myArray as $value) {
$where = $where + "'" + $value + "'"
}
$where = $where + " )"

SQL search using PHP arrays

How to search multiple fields in a MySQL database with a PHP array.
For example, search fields like place_name, admin_name1, and admin_name2 using an array of ["Cambridge","Massachusetts","US"] with using the wildcard %
Below is the exact structure of database
Imagining your array index names are the same as your table column names:
$query = "select * from tableName";
$arrCount = count($arrName);
$i=1;
if($arrCount) > 0){
$query .= " where";
foreach($arrName as $key->$val){
$query .= $key." LIKE '%".$val."%'";
if($i <= $arrCount)
$query .= " AND";
$i++;
}
}
Then run the query!
$array = ["Cambridge","Massachusetts","US"];
$list = implode(",", $array);
Then select:
... WHERE place_name IN($list) OR admin_name1 IN($list) OR admin_name2 IN($list)
Try this
$fields = array("place_name", "admin_name1", "admin_name2");
$kwd = array("Cambridge","Massachusetts","US");
$condition = array();
$n = 0;
foreach($fields as $field){
$condition[] .= $field." LIKE '%".$kwd[$n]."%'";
$n++;
}
$condition = implode(" AND ", $condition);
echo $qry = "SELECT * FROM `table` WHERE ( ".$condition." )";

convert | separated values into new table using PHP

Edit: I forgot to add the explode part that I'm having the issues with. I need the query result exploded.
I have been messing with this for a while and have a workable procedure in mysql, however I want to accomplish this as part of a larger script. I have a table filled with IDs and several columns of data with "|" separated values. How can I use or edit the below PHP to query and insert normalized results into a new table?
If I run this with an actual string: "40|180|408|360|40|166|80|59"; It will insert values (not the ID, which I also need) but when I try to pass in query results, I get "Array to string conversion" errors. Any guidance would be appreciated.
$query = "Select id, imageSize from T1";
$result = mysqli_query($conn, $query);
$myArray = explode('|', $result);
foreach($myArray as $value) {
$sql = "INSERT INTO testExplode VALUES ($value)";
$result = mysqli_query($conn, $sql);
}
If you want to insert all of your results then:
$query = "Select id, imageSize from T1";
$myArray = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($myArray)) {
$sql = "INSERT INTO testExplode VALUES (" . mysqli_real_escape_string($conn, $row['imageSize']) . ")";
mysqli_query($conn, $sql);
}
//If just only one:
$query = "Select id, imageSize from T1";
$myArray = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($myArray);
$sql = "INSERT INTO testExplode VALUES (" . mysqli_real_escape_string($conn, $row['imageSize']) . ")";
mysqli_query($conn, $sql);
NOTE:
Avoid sql injecions by escaping your variables in your querys.
EDIT:
Based on the OP comment.
$query = "Select id, imageSize from T1";
$myArray = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($myArray)) {
$values = explode('|', $row['imageSize']);
foreach ($values as $value) {
$sql = "INSERT INTO testExplode VALUES (" . mysqli_real_escape_string($conn, $value) . ")";
mysqli_query($conn, $sql);
}
}

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

How can I query to mysql with ARRAY in condition

A have names of rows in array
$arr = array(fir, seco, third);
how can I query mysql like:
$query = "SELECT * FROM $table where fir=0 and seco=0 and third=0";
but using array.
and
$query = "update $table SET fir='$ma', seco='$ma', third='$ma'";
but using array.
For search you can fire below query -
$str = implode(",", $arr);
$query = "SELECT * FROM $table where 0 IN ($str)";
But for update you have to use query what you have written.
easy,
$arr = array(fir, seco, third);
for(int i = 0;i<arr.lenght;i++)
{
$query = $query + " and " + arr[i] + "=" + $ma;
}
This is what I would do...
$fir = $arr[0];
$seco = $arr[1];
$third = $arr[2];
$query = "UPDATE $table SET $fir = '$ma', $seco = '$ma', $third = '$ma'";
Not sure if there is a more optimal answer, but you could use a for loop to create the SQL statement:
<?php
$arr = array(fir, seco, third);
$query = "SELECT * FROM $table where ";
$count = count($arr);
for($i=0;$i<$count;$i++){
$query .= ($i==$count-1) ? "$arr[$i]=0" : "$arr[$i]=0 and ";
}
echo $query;
?>
Echoes SELECT * FROM $table where fir=0 and seco=0 and third=0. You can do the same with the UPDATE SQL statement.
Update
Also, you could implode the array, like in Suresh Kamrushi's answer, and use the following code:
<?php
$arr = array(fir, seco, third);
$str = implode(',',$arr);
$query_one = "SELECT * FROM $table WHERE ($str) = (0,0,0)";
echo $query_one;
?>
The UPDATE query would still need a for loop though, I think.

Categories