interleaving arrays for mysql update - php

I have two arrays, one containing the field names which are imploded into a string called $fields, and one containing the data imploded into $data.
When data is first entered using the INSERT command the query looks like...
mysql_query("UPDATE table ($fields) VALUES ($data)")
(BTW: all data is sanitised)
My goal is to build a mysql UPDATE statement where the syntax is
mysql_query("UPDATE table SET $field1=$data1, $field2=$data2 ...")
and update all fields at once, so I need to combine the two arrays to build the alternating field/data/field/data structure instead of all of the fields followed by all of the data.
My idea is to use array_combine or array_merge and then implode into a string that will then set the function to
mysql_query("UPDATE table SET $imploded-combined-arrays")
I recognise that this won't work as the "glue" of the implode statement has two different values depending upon whether it is equating or separating field/data pairs.
How can I step through both arrays and build a string that is appropriate for the UPDATE syntax?
Thanks,
Cam

Try this
$a = array('key1', 'key2', 'key3');
$b = array('value1', 'value2', 'value3');
$c = array_combine($a, $b);
foreach($c as $key=> $value){
$result[]=$key."='". $value."'";
}
$updatefields= implode (', ', $result);
echo ("update table set " .$updatefields);
OUTPUT
update table set key1='value1', key2='value2', key3='value3'
DEMO

$names = array ('foo', 'bar');
$values = array ('hello', 'world');
$pairs = array ();
foreach ($names as $i => $name)
{
$value = $values [$i];
// $name = mysql_real_escape_string ($name);
// $value = mysql_real_escape_string ($value);
$pairs [] = "`$name` = '$value'";
}
echo ("UPDATE t SET " . implode (', ', $pairs));
For me outputs is:
UPDATE t SET `foo` = 'hello', `bar` = 'world'

Related

Joining array values into string in MySQL multiple insert

In a form, multiple Checkbox values to be inserted into database:
My Code:
Array: ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )
$a = $_POST['id']; // data from form
$query = "INSERT INTO abc(`x`,`y`,`z`) VALUES " . implode (",","(NULL,$a,'1')");
mysqli_query($dbc,$query);
There seems to be a problem with implode function. How do you concat array using implode?
// Expected output
INSERT INTO abc(`x`,`y`,`z`) VALUES (NULL,1,'1'),(NULL,2,'1'),(NULL,3,'1'),(NULL,4,'1'),
Column y of table abc needs to loop with $a.
If you want to create a batch multiple insertions, first build the batches first, then implode those batches:
$multiple = array_map(function($e) use($dbc) {
$e = $dbc->real_escape_string($e);
return "(NULL, $e, '1')";
}, $a);
$query = "INSERT INTO abc(`x`,`y`,`z`) VALUES " . implode (',', $multiple);
mysqli_query($dbc,$query);
Sidenotes: Its not VALUE, Its VALUES. And remember to use the correct quotes on identifiers. Its supposed to be backticks not single quotes.
INSERT INTO abc('x','y','z') // NOT OK
INSERT INTO abc(`x`,`y`,`z`) // OK
Here you do implode concate.
$query = "INSERT INTO abc('x','y','z') VALUE " . "('" . implode("','", $a) . "')";
Youre using wrong arguments in implode implode() and check your insert query you must use values instead of value
$query = "INSERT INTO abc('x','y','z') VALUES (".implode(",",$a).")";
$a = array(1,2,3,4);
$string = '';
foreach($a as $v){
$string .= "(NULL, $v, 1),";
}
$string = substr($string,0,-1);
$query = "INSERT INTO abc('x','y','z') VALUES $string";
As per your comments in question, This should be your code:
foreach($a as $item)
{
$str[] = "(NULL, '$item', 1)";
}
$query = "INSERT INTO abc(x,y,z) VALUES ".implode(',', $str);
So, you were doing two mistakes:
VALUE should be VALUES
Using implode at wrong place

How to iterate through database results, compare each value to that in an array and return the matching id?

I am trying to build a function that will be given an array. and from this array, iterate through an entire table in the database trying to find a match. If it does find a match. I would like it to echo out the ID of that match from the database table.
If possible I would also like it to say if it found any close matches?
What's making this tricky for me is that it needs to match all values despite their order.
for example, if the function is given this array:
$array = array(1,2,3,4,5)`
and finds this array in the database:
$array = array(2,3,5,1,4)
it should consider this a match
Also, if it finds
array(1,2,3,4,5,6)
It should output this this as a match except for value 6.
Let me refrase your question, is this correct?
Based on an array of ID's, return all records whose ID's are in the array.
If so, use the IN operator:
SELECT *
FROM tableName
WHERE columnName IN (value1, value2, value3, etc.)
So first we need to transform the given array into a comma-seperated list:
$comma_seperated = implode(', ', $array);
Now we have a comma-seperated list we can use in our query:
$comma_seperated = implode(', ', $array);
$query = "SELECT *
FROM tableName
WHERE id IN (" . $comma_seperated . ")";
// execute query, don't use mysql_* functions, etc. ;)
You could use any of the options:
option 1:
$array = array(1,2,3,4,5);
$query = "SELECT id FROM youtable WHERE id IN(".implode(",",$array).")";
option 2:
$array = array(1,2,3,4,5);
$query = "SELECT id FROM yourtable";//Select ids
Now iterate through query results, say results are stored in $query_results,
$result=array();
foreach($query_results as $row){
if(in_array($row['id'],$array)){
$result[] = $row['id'];
}
}
You can use array difference to get the result just run the code and you will understand
Case 1
$array1 = array(1,2,3,4,5);
$array2 = array(1,2,3,4,5,6);
$result = array_diff($array1, $array2);
print_r($result);
Case 2
$array1 = array(1,2,3,4,5);
$array2 = array(1,2,3,4,5,6);
$result = array_diff($array2, $array1);
print_r($result);
And after that you can the count of $result and put it in your logic.
Case 1:
Maybe you can select the unique values from the database.
SELECT DISTINCT unique_values_that_need_for_compare_column FROM table
This SQL result will be the $databaseValues variable value.
Than iterate through the array that the function gets.
foreach ($functionArray as $value) {
if (in_array($value, $databaseValues)) {
// you have a match
echo $value;
}
}
Case 2:
Or you can make a query for every value:
foreach ($functionArray as $value) {
$query = "SELECT COUNT(*) as match FROM table WHERE unique_values_that_need_for_compare_column = " . intval($value);
// fetch the result into the $queryResult variable and than check
if ($queryResult['match']) {
// you have a match
echo $value;
}
}

How to insert cookie data into mysql database php?

I have an array of data saved in cookie, like this
1:good,2:accelent,3:bad,4:good,fname:Ahmad,lname:Riaz,title:Developer,org:Magiclamp,email:Riaz#khan.com
here i want to save this data in different tables
This in one table
1:good,2:accelent,3:bad,4:good
and this in another table
fname:Ahmad,lname:Riaz,title:Developer,org:Magiclamp,email:Riaz#khan.com
how can i solve this problem
Read the cookie using $_COOKIE: $cookie_val = $_COOKIE['NAME'];
Split the input using explode(): $cookie_array = explode(",", $cookie_val);
From the result array use the values needed: $cookie_array[0], $cookie_array[1] ...
Clean the values before insertion into the db.
<?php
$str = "1:good,2:accelent,3:bad,4:good,fname:Ahmad,lname:Riaz,title:Developer,org:Magiclamp,email:Riaz#khan.com";
$rows = explode(',', $str);
$data['table1'] = $data['table2'] = array();
foreach($rows as $k => $v) {
$a = explode(':', $v);
$data[(is_numeric($a[0]) ? 'table1' : 'table2')][$a[0]] = $a[1];
}
var_dump($data);
?>
That will split the data into two arrays.

MYSQL insert comma separated values into separate fields?

I know its a strange question, but I have one input field that does a live search for locations. The final value is displayed like this:
State,Suburb,Post Code
NSW,Sydney,2210
What I need to do now is split the three values into single values and update them into my separate fields for one row.
I don't want to update multiple rows but just one.
e.g.:
fields ( state | suburb | postcode )
values ( NSW | sydney | 2210 )
What php commands would I use to split those commas off and create single $values for each item?
Use explode on the string.
$values = 'A,B,C,D';
$values = explode(',', $values);
Each item can then be accessed from an array indexed from 0.
$val = "NSW,Sydney,2210";
$valArr = explode(",", $val);
$query = "UPDATE MyTbl SET State = '$valArr[0]', Suburb = '$valArr[1]', Post_Code = '$valArr[2]' WHERE ...";
The easiest way I think, see the manual for explode:
$result_array = explode(',', $your_variable);
list($state, $suburb, $postcode) = explode(',', $value);
Would this work?
$header = "State,Suburb,Post Code"
$items = explode(",", $input)
$output = implode("|", $items)
so the output would become State|Suburb|Post Code
to access each value separately, you can use $items[0], $items[1] ..
$data = "NSW,Sydney,2210"
$items = explode(",", $input)
$output = implode("|", $items)
so the output would become NSW|Sydney|2210

How to create a string that contains the keys of a given array in PHP?

I have an array holding this data:
Array (
[1402377] => 7
[1562441] => 7
[1639491] => 9
[1256074] => 10
)
How can create a string that contains the keys of the above array?
Essentially, I need to create a comma separated string that consists of an array's keys
The string would look like: 'key','key','key'
Do I need to create a new array consisting of the keys from an existing array?
The reason I need to do this is because I will be querying a MySQL database using a WHERE in () statement. I would rather not have to query the database using a foreach statement. Am I approaching this problem correctly?
I've tried using a while statement, and I'm able to print the array keys that I need, but I need those keys to be an array in order to send to my model.
The code that allowed me to print the array keys looks like this:
while($element = current($array)) {
$x = key($array)."\n";
echo $x;
next($array);
}
$string = implode(',', array_keys($array));
By the way, for looping over an array consider not using current and next but use foreach:
foreach ($array as $key => $value) {
//do something
}
This will automatically iterate over the array until all records have been visited (or not at all if there are no records.
$keys = array_keys($array);
$string = implode(' ',$keys);
In your case, were you are using the result in a IN clause you should do:
$string = implode(',', $keys);
$yourString = '';
foreach($yourArr as $key => $val) {
$yourString .=$key.",";
}
echo rtrim($yourString, ",");
//OR
$yourString = implode(",", array_keys($yourArray));
See : array_keys
implode(', ', array_keys($array));
Use php array_keys and implode methods
print implode(PHP_EOL, array_keys($element))
The string would look like: 'key','key','key'
$string = '\'' . implode('\',\'', array_keys($array)) . '\'';
Imploding the arguments and interpolating the result into the query can cause an injection vulnerability. Instead, create a prepared statement by repeating a string of parameter placeholders.
$paramList = '(' . str_repeat('?, ', count($array) - 1) . '?)'
$args = array_keys($array);
$statement = 'SELECT ... WHERE column IN ' . $paramList;
$query = $db->prepare($statement);
$query->execute($args);

Categories