Convert a PHP array to an SQL statment? - php

I'm trying to convert an array (key/value) to be an SQL statement.
I'm using MYSQLi like such:
if(!$result = $mysqli->query($sql)){throw new Exception("SQL Failed ".__file__." on line ".__line__.":\n".$sql);}
I have an array like such:
Array
(
[database] => Array
(
[cms_network] => Array
(
[network_id] => 61
[network_name] =>
[network_server_mac_address] => 00:1b:eb:21:38:f4
[network_description] => network
[network_thermostat_reporting_rate] => 5
[network_server_reporting_rate] => 5
[network_data_poll_rate] => 5
[network_created_by] => 38
[network_modified_by] => 1
[network_network_id] => 8012
[network_language] => en
[network_hotel_id] => 68
[network_channel] => 0
[network_deleted] => 0
[network_reported_network_id] => 8012
[network_rooms] => 4
)
)
)
How can I convert [cms_network] to look like this:
$sql = "UPDATE cms_network set network_id='61', network_name='',
network_server_mac_address = '00:1b:eb:21:38:f4', .... WHERE network_id='61'"
I'm more interested in knowing how to concatenate the key=>value pair of the array to be key='value' in my select statement.
Thanks for the help!

If you use the VALUES syntax, you could do it in one fell swoop.
mysql_query("
UPDATE MyTable
( . implode(',', array_keys($array['database']['cms_network'])) . ")
VALUES ('" . implode("','", $array['database']['cms_network']) . "')
");
This, of course, assumes that the data is already escaped.
EDIT: Tidier version that's easier to read and maintain:
$fields = implode(',', array_keys($array['database']['cms_network']));
$values = implode("','", $array['database']['cms_network']);
mysql_query("UPDATE MyTable ($fields) VALUES ('$values')");

I suggest you populate an array with formatted key/value pairs, then implode them at the end. This is an easy way to add the required , between each key/value:
$fields = array();
foreach($array['database']['cms_network'] as $key => $value) {
// add formatted key/value pair to fields array
// e.g. format: network_id = '26'
$fields[] = $key . " = '" . $value . "'";
}
$fields = implode(', ', $fields);
// build your query
$query = "UPDATE cms_network SET " . $fields . " WHERE network_id = " . $array['database']['cms_network']['network_id'] . " LIMIT 1";
// process it...
This will (SQL wise) be inserting every value as a string, which is obviously incorrect with integer columns etc. It should still work anyway, but if not you'll need to put in a conditional statement for whether to wrap the value in quotes or not, like this:
foreach(...) {
if(is_numeric($value))
$fields[] = $key . ' = ' . $value;
else
$fields[] = $key . " = '$value'";
}
Although this should probably relate to your database column type rather than the PHP variable type. Up to you, they should work fine with quotes around integers.

This should work.
$update_query = "UPDATE `cms_network` SET ";
$count = 0;
foreach($array['database']['cms_network'] as $key => $value) {
if ($count != 0) {
$update_query = $update_query.",".$key."=".$value;
} else {
$update_query = $update_query.$key."=".$value;
}
$count++;
}
$update_query = $update_query." WHERE ".cms_network."=".$array['database']['cms_network'];
mysql_query($update_query);

Related

Why I cant update rows with PDO using prepare function?

I have an SQL $query like this;
UPDATE `tags` SET `tags.name` = :name,
`tags.slug` = :slug,
`tags.date_published` = :date_published,
`tags.meta_title` = :meta_title,
`tags.meta_description` = :meta_description,
`tags.meta_keywords` = :meta_keywords
WHERE `tags.id` = :id
And my $values array;
Array
(
[:name] => iphone
[:slug] => iphone
[:date_published] => 2016-03-27
[:meta_title] => iphone Yazıları
[:meta_description] => iphone hakkında son gelişmeler ve faydalı bilgiler.
[:meta_keywords] => iphone yazıları, iphone hakkında bilgiler, iphone haberleri
[:id] => 24
)
I'm trying to update one row with PDO's prepare function;
$sth = $this->db->prepare($query);
$sth->execute($values);
echo "affected rows: ".$sth->rowCount(); // prints 0
return $sth->rowCount() ? true : false;
And I get no errors but rows are not affected after execute the query. Where is my mistake?
mysql tags table
edit:
I'm creating values array like this;
$params = array(
"id", "name", "slug", "date_published",
"meta_title", "meta_description", "meta_keywords");
$values = array();
foreach ($params as $key) {
#$values[$key] = $_POST[$key];
}
And this is how I create the query;
$query = "UPDATE `$table` SET";
$values = array();
/* Add field names and placeholders to query. */
foreach ($params as $key => $value) {
$query .= " `{$table}.{$key}` = :" . $key . ",";
$values[":" . $key] = $value;
}
/* Remove last comma. */
$query = substr($query, 0, -1);
/* Build where condition. */
if ($cond) {
$query .= " WHERE ";
foreach ($cond as $key => $value) {
$query .= " `{$table}.{$key}` = :" . $key . ",";
$values[":" . $key] = $value;
}
/* Remove last comma. */
$query = substr($query, 0, -1);
}
You're escaping the column names incorrectly. For example, the back ticks should not enclose the whole of tags.name, but rather the table and column names separately:
`tags`.`name`
Checking the output of PDO::errorInfo() confirms this (emulated prepares must be set to false in order to see this, however).
General notes:
You don't need to specify the colon prefix for the keys of the array being bound (likewise when explicitly binding columns via bindParam() or bindValue()).
You should avoid using back ticks in your PDO queries. They're a MySQL-specific feature, and PDO is not a SQL abstraction layer (thereby preventing one of the major benefits of PDO - portability).

Store php foreach loop in string

We have an Array Name valArray which is something like this :
$valArray = array (
name => 'Rahul',
Address => 'New Delhi',
Pass => '1234',
class => '10th',
School => 'DPS',
Roll => '134567',
)
which generates dynamicaly, So, Actually we want is to run this type of sql query,
$query = "insert into table_name set
foreach($valArray as $key => $value) {
$key = "$value",
}
";
and Statically which should be something like this :
$query = "insert into table_name set
name = 'Rahul',
Address = 'New Delhi',
Pass = '1234',
class = '10th',
School = 'DPS',
Roll = '134567'
";
I Know this is syntactically wrong but is there any way to perform this type of action.
$sql = "insert into $table(" . implode(',', array_keys($valArray)) . " values('" . implode("','", array_values($valArray)) . "')";
the call to array_values isn't necessary, but better illustrates the idea I think
edit: quoted values; they should be escaped too

Using two arrays with different keys in an mysql update query

I have a array like this
$outputs:
269 => string ' SUN: 2.495' (length=13)
510 => string ' SUN: 1.416' (length=13)
Another Array like this
$filenames:
0 => string 'Hi35
' (length=5)
1 => string 'He_41
' (length=6)
And to update the respective values i tried writing a code like
foreach($outputs as $key => $value){
$sql = "UPDATE Store SET D='".$value."' WHERE `Index` = '".$filenames[$key]."'";
mysql_query($sql);
}
But then there is no $filenames[$key] value, because the key value for $outputs starts with 269. This is only one case, the key value could be anything.
I also tried the other way around. i.e.
I combined both the array first
$arr3 = array_combine($outputs, $filenames);
And then tried to Put the combined array in SQL query like
foreach($arr3 as $key => $value){
$sql = "UPDATE Store SET D='".$key."' WHERE `Index` = '".$value."'";
mysql_query($sql);
}
BUT this dint work.. A help from your side will really be appreciated...
You can do something like this
$outputs = array(
'269' => 'SUN: 2.495',
'510' => 'SUN: 1.416'
);
$filenames = array(
'0' => 'Hi35',
'1' => 'He_41'
);
$array_complete = array_combine($filenames, $outputs);
foreach($array_complete as $key => $val)
{
echo "UPDATE Store SET D='".$val."' WHERE `Index` = '".$key."'" . '<br>';
}
This will output
UPDATE Store SET D='SUN: 2.495' WHERE `Index` = 'Hi35'
UPDATE Store SET D='SUN: 1.416' WHERE `Index` = 'He_41'
Then I would like to remember you that mysql_ functions are deprecated so i would advise you to switch to mysqli or PDO
Your code doesn't look good at all mate, but here is a hack for that:
$num_outputs = count($outputs);
$index = 0;
foreach($outputs as $key => $value) {
$sql = "UPDATE Store SET D='".$value."' WHERE `Index` = '".$index."'";
mysqli_query($sql);
$index++;
}

php use two arrays in an mysql update query

Hey guys i want to use two arrays in on mysql UPDATE query. So here is what i have:
For example:
$ergebnis:
Array ( [0] => 100 [1] => 200 [2] => 15 )
$Index:
Array ( [0] => 3 [1] => 8 [2] => 11 )
And this is what i tried:
UPDATE `lm_Artikel`
SET Bestand='".$ergebnis."'
WHERE `Index` = '".$Index."'
This query seems not to work. I don't know why i enabled php error reporting and there are no errors and when i run the query it doesn't change anything in my database. Can anyone see what i did wrong?
You need to do it for each element of your arrays, hence, you can use the foreach() function:
foreach($ergebnis as $key => $value){
$sql = "UPDATE lm_Artikel SET Bestand='".$value."' WHERE `Index` = '".$Index[$key]."'";
mysqli_query($sql);
}
P.S. There could well be a pure-sql alternative but I'm not too SQL-hot, so I'll leave it to someone who has more expertise.
Also, please note that it may be easier for you to set the index as the array keys:
$ergebnis = Array(3=>100, 8=>200, 11=>15);
And then the foreach() would look a little better:
foreach($ergebnis as $key => $value){
$sql = "UPDATE lm_Artikel SET Bestand='".$value."' WHERE `Index` = '".$key."'";
mysqli_query($sql);
}
Fellow,
it looks like that your database field is an int value so you can try doing it value by value, like this:
foreach( $Index as $key => $i ) :
$query = "UPDATE lm_Artikel SET Bestand=".$ergebnis[$key]." WHERE Index = " . $i;
mysqli_query($query);
endforeach;
Try it.
You are susceptible to SQL injections
You cannot use arrays in queries. A query is a string, arrays are not.
You either need to use a loop or use a CASE statement:
UPDATE `lm_Artikel`
SET `Bestandteil` = CASE `Index`
WHEN <insert id> THEN <insert value>
WHEN <insert other id> THEN <insert other value>
<etc>
END
$data_db = array( '3' => 100,
'8' => 200,
'11' => 15);
foreach($data_db as $key=>$value) {
$q = 'UPDATE lm_Artikel SET Bestand=' . $value . ' WHERE `Index` = ' . $key;
mysqli_query($sql);
}
Assuming these are value pairs, i.e. $ergebnis[0] is for $Index[0] and so forth.
foreach ($ergebnis as $key => $value) {
$sql = 'UPDATE lm_Artikel SET Bestand=' . (int)$value . ' WHERE `Index` = ' . (int)$Index[$key];
// execute query...
}
A few notes:
You are open to SQL Injection. I used (int) as a quick patch.
I would encourage you to look into Prepared Statements.
You should avoid naming your columns SQL keywords, e.g. Index.

access multidimensional array

This is sort of a follow up to my last question. Im trying to access the data of a multidimensional array so as to insert into a database. Ive been looking all over the forums as well as trying different things on my own but cant find anything that works. Here is what the array looks like:
$_POST[] = array[stake](
'stakeholder1' => array(
'partner'=> 'partner',
'meet'=> 'meet'
),
'stakeholder2' => array(
'partner'=> 'partner',
'agreement'=> 'agreement',
'train'=> 'train',
'meet'=> 'meet'
),
);
I'm trying to do somthing like ( UPDATE list WHERE stakeholder = "stakeholder1" SET partner =1, meet =1 ) depending on which stakeholder/choices were selected (theres four different options). Thanks,
This one will set 1 for checked options, and 0 for unchecked options (otherwise you will miss some data updates).
$optionsList = array('partner', 'agreement', 'train', 'meet');
$stakeHolders = array('stakeholder1', 'stakeholder2', ...);
foreach($stakeHolders as $stakeHolder)
{
$selectedOptions = $_POST[$stakeHolder];
$arInsert = array();
foreach($optionsList as $option)
$arInsert[] = '`'.$option.'` = '.intval(isset($selectedOptions[$option]));
$sql = "UPDATE list
SET ".implode(", ", $arInsert)."
WHERE stakeholder = '".mysql_real_escape_string($stakeHolder)."'";
// TODO: execute $sql (mysql_query(), or PDO call,
// or any wrapper you use for DB)
}
$query = '';
foreach ($_POST as $k => $v) {
$query .= "UPDATE list WHERE stakeholder = '$k' SET " . implode(" = 1," $v) . ",";
}
$query = substr($query, 0, -2); //Get rid of the final comma
This should give you something like what you are looking for, if I understand your database schema correctly.
If you are using PDO, you could do something like:
foreach($_POST as $stakeholder => $data) {
$sth = $dbh->prepare('UPDATE `list` SET `' . implode('` = 1, `', array_keys($data)) . '` = 1 WHERE stakeholder = ?');
$sth->execute(array($stakeholder));
}
Be sure to sanitize the user input (keys of the data...).
foreach($main_array as $key => $sub_array) {
$sql = 'UPDATE list
WHERE stakeholder = "{$key}"
SET ';
$sets = array();
foreach($sub_array as $column_value)
$sets[] = $column_value." = 1";
$sql = $sql.implode(',', $sets);
}

Categories