Insert multidimensional array information into database - php

This seems like it would have a really easy solution...but I've had a hard time figuring it out. I need an array to go into a database. For example:
$usa = array(
'idaho' => array(
county1 => array(
'pocatello', 'arimo', 'downey'
),
county2 => array(
'bear', 'cuprum', 'mesa'
)
'iowa' => array(
county1 => array(
'des moines', 'adel', 'desoto'
),
county2 => array(
'douglas', 'grant', 'jasper'
)
);
I tried this method of inserting into the database:
foreach($usa as $state => $county){
foreach($county as $name => $city){
$s=$state;
$county_name = strtolower($name);
$city = strtolower($city);
$us = "INSERT INTO us
SET state='{$s}',county='{$county_name}',city='{$city}'
";
$us_result = mysql_query($us,$connection);
}
}
I believe the problem is the foreach (passing the state variable into the second foreach loop). I have tried this a number of different ways. Thanks in advance for your help!
***Note: everything works great when I remove the $s=$state variable and the state='{$s}' portion of the insert. I still cant get it to insert the state

There are two major problems.
First, your array isn't delimited properly and it's better to use a single or double quote for the county names, which you are referring to as strings anyway:
$usa = array(
'idaho' => array(
'county1'=>array(
'pocatello', 'arimo', 'downey'
),
'county2'=>array(
'bear', 'cuprum', 'mesa'
)),
'iowa' => array(
'county1'=>array(
'des moines', 'adel', 'desoto'
),
'county2'=>array(
'douglas', 'grant', 'jasper'
))
);
Secondly, there should be one more foreach loop to account for city names:
foreach($usa as $state => $county){
foreach($county as $name => $city){
foreach ($city as $cityname) {
$s = $state;
$county_name = strtolower($name);
$city = strtolower($cityname);
$us = "INSERT INTO us SET state='{$s}',county='{$county_name}',city='{$city}'";
echo $us.'<br>';
}
}
}
Hope this helps!

First. As #itsmeee stated, you were missing one more foreach that iterates through the array of cities in that county. Besides that, your input array is missing 2 close parens to wrap the array of data per state.
If you fix that I would just do:
$us = "INSERT INTO us (state, county, city) VALUES ";
$values = array();
foreach($usa as $state => $county){
foreach($county as $name => $cities){
foreach($cities as $city){
$county_name = strtolower($name);
$city = strtolower($city);
$values[] = "('{$state}','{$county_name}','{$city}')";
}
}
}
$us .= join(',',$values);
$us_result = mysql_query($us,$connection);
This would build the insert string and do all the inserts in one shot. You could also do individual inserts but for a data set this small doing one large insert is more efficient.
Good Luck!

Your INSERT query is incorrect.
Try this:
$us = "INSERT INTO us (state, county, city) VALUES ('" . mysql_real_escape_string ($s) . "', '" . mysql_real_escape_string ($county_name) . "', '" . mysql_real_escape_string ($city) . "')";

Seems like you've missed one more foreach:
foreach($county as $name => $cities) {
foreach ($cities as $city) {
....

Related

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

Separate two array values from one key and insert to database in PHP

I designed the system for booking rooms and store the data by multi-dimensional array form.
Here is the array (data):
$recordBooking = array(
"111"=>array(
"date"=>array(
"29/10/2014"=>array(
array(
"from"=>1,
"to"=>3,
"user"=>"Amy",
"username"=>"CB34"
),
array(
"from"=>4,
"to"=>5,
"user"=>"Chars",
"username"=>"AA13"
)
),
"30/10/2014"=>array(
array(
"from"=>2,
"to"=>3,
"user"=>"Chars",
"username"=>"AA13"
),
array(
"from"=>3,
"to"=>6,
"user"=>"Gary",
"username"=>"SF11"
)
),
"02/11/2014"=>array(
array(
"from"=>1,
"to"=>3,
"user"=>"Billy",
"username"=>"V214"
)
),
.......
)
)
);
Also I was using the foreach-loop to separate the array values and store those data. And I using an array, $BookArrRecord, for gathering the values and insert into the database. It caused the error that $BookArrRecord can store the last values of each date only. Can anyone helps me to find out the problem and how to improve?
foreach($recordBooking as $key => $value){
$rmNum[] = $key;
foreach($value as $k => $v){
foreach($v as $bookDate => $array){
$bookingDate[] = $bookDate;
foreach($array as $room => $info){
foreach($info as $period =>$fromTo){
if($period=="username"){
$userID[] = $fromTo;
}
if($period=="from"){
$from[] = $fromTo;
}
if($period=="to"){
$to[] = $fromTo;
}
}
}
}
}
}
for($rmCount=1;$rmCount<count($userID);$rmCount++){//get the $userID to set the rows of $rmNum
$rmNum[]+=$rmID[0];
}
$BookArrRecord = array();
foreach($rmNum as $key => $value){
$BookArrRecord[] = "('" . $userID[$key] . "', '" . $rmNum[$key] . "', '". $bookingDate[$key] . "', '" . $from[$key] . "', '" . $to[$key] . "')";
}
The sql query:
$bookingInformation = "INSERT INTO `bookRecord` (`userID`, `room_Number`, `date`, `frome`, `to`)
VALUES " . implode(',', $BookArrRecord);
The checking of the query:
if(!mysql_query($bookingInformation, $dbConnection)){
die("Cannot access operation of Database(bookRecord): " . mysql_error()) . "<br>";
}else{
echo "Records added in table: BookingDate " . "<br>";
}
The results shows by using var_dump:
array(268) {
[0]=>
string(38) "('CB34', '111', '29/10/2014', '1', '3')"
[1]=>
string(38) "('AA13', '111', '30/10/2014', '4', '5')" //the date is wrong
[1]=>
string(38) "('AA13', '111', '02/11/2014', '2', '3')"
......
}
Thanks for any help.
I think your problem is that you have lots of different arrays ($userID, $rmNum, $bookingDate etc) which you're adding values to at different times. This makes it hard to keep track of which value in each array corresponds to which values in the other arrays. (It is possible, but tricky and likely leads to bugs).
An easier solution is to handle adding records to $BookArrRecord inside your foreach loops. That way you know that all the different values will be consistent.
For example:
$BookArrRecord = array();
$roomNumber = 1;
foreach($recordBooking as $key => $value){
$rmNum[] = $key;
foreach($value as $k => $v){
foreach($v as $bookDate => $array){
foreach($array as $room => $info){
$BookArrRecord[] = "('" . $info['username'] . "', '" . $roomNumber . "', '". $bookDate . "', '" . $info['from'] . "', '" . $info['to'] . "')";
$roomNumber++;
}
}
}
}
var_dump ($BookArrRecord);
Notice I've removed the innermost array. There's no need to loop over an array when you know which keys you're looking for.
As an aside, it's generally bad practice to include variables directly in a database query. You should escape them first. As this is a hardcoded array of values that you've specified, it's unlikely to go wrong now. But as soon as you start using any user-inputed values, make sure you escape them before they go anywhere near the query!

Convert a PHP array to an SQL statment?

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

Insert JSON array in mysql db from a php file

Hello i have a JSon array like this
Array
(
[NTAy] => ALFA ROMEO
[NTA0] => AUDI
[NTEx] => BMW
[NjAy] => CHEVROLET
[NTEz] => CHRYSLER
[NTE0] => CITROËN
[NjAz] => DACIA
[NjQ5] => DAEWOO
[NTE3] => DAIHATSU
)
and I have to insert it in a database row by row, I used
foreach ($mata as $marca_id => $marca_name){
$line = $line. "','" . $marca_id . "','". $marca_name . "','". $marca_name;
}
$line = substr($line, 0, strlen($line)-1);
$values[$i] = $line;
++$i;
$values =implode ( $values);
echo $values;
echo "<br />";
but at the mysql insert
$data = mysql_query(" INSERT INTO jos_virtuemart_categories_ro_ro (virtuemart_category_id, category_name, slug)
VALUES " .$values)
I get an error and can't get it to work. Can someone help me please?
foreach ($mata as $marca_id => $marca_name) {
$id = intval($marca_id);
$name = mysql_real_escape_string($marca_name);
$values = "$id, '$name', '$name'";
mysql_query("INSERT INTO jos_virtuemart_categories_ro_ro (virtuemart_category_id, category_name, slug) VALUES ($values)");
}
Why not use prepared statements? Especially if you're taking user generated data and entering it into your database.
That and it looks like you're final SQL query will look like this
INSERT INTO jos_virtuemart_categories_ro_ro (virtuemart_category_id, category_name, slug)
VALUES 'NTAy','ALFA ROMEO','ALFA ROMEO','NTA0','AUDI','AUDI' etc
You would have to break this up into multiple queries

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++;
}

Categories