Insert JSON array in mysql db from a php file - php

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

Related

Looping through Array Values with $SQL output

I have a list of serialized data that I unserialize and store into an array.
$employee_data = unserialize($entry, '63');
Which results in an expected output:
Array ( [0] =>
Array ( [First] => Joe
[Last] => Test
[Birth Date] => 01/01/2011
)
[1] =>
Array ( [First] => Mike
[Last] => Miller
[Birth Date] => 01/01/1980
)
)
Ive been trying, unsuccessfully, to insert these records into a table in MySQL using foreach() or something like:
$employee_array = array();
$k = 1;
for($n=0; $n<count($employee_data); $n++ ){
$employee_array['employee_first_name'.$k] = $employee_data[$n]['First'];
$employee_array['employee_last_name'.$k] = $employee_data[$n]['Last'];
$employee_array['employee_birthdate'.$k] = $employee_data[$n]['Birth Date'];
$SQL = "INSERT INTO employee_test (
employee_first_name,
employee_last_name,
employee_birthdate
)
VALUES (
'$employee_first_name.$k',
'$employee_last_name.$k',
'$employee_birthdate.$k'
)"
$k++;
};
Each employee in the array needs to be entered into a new row in the table, however the number of employees will vary from 1 to 10+
We've tried
foreach($employee_array as $key => $value)
with the same results.
The actual results we're hoping for is the SQL Statement to be:
insert into employee_test(
employee_first_name,
employee_last_name,
employee_birthdate)
VALUES(
'Joe',
'Test',
'01/01/2011');
insert into employee_test(
employee_first_name,
employee_last_name,
employee_birthdate)
VALUES(
'Mike',
'Miller',
'01/01/1980');
Keep in mind that your sql statement is not escaped. For example, a name with an apostrophe like "0'neil" will break your sql. I would also familiarise yourself with php's foreach: https://www.php.net/manual/en/control-structures.foreach.php.
I'm not sure exactly what you're trying to accomplish by adding the index to the name and sql value, but I would do something like this:
foreach($employee_data as $key => $value){
// $employee_array is not necessary
$employee_array[$key]['employee_first_name'] = $value['First'];
$employee_array[$key]['employee_last_name'] = $value['Last'];
$employee_array[$key]['employee_birthdate'] = $value['Birth Date'];
// Needs escaping
$SQL = "INSERT INTO employee_test (
employee_first_name,
employee_last_name,
employee_birthdate
)
VALUES (
'{$value['First']}',
'{$value['Last']}',
'{$value['Birth Date']}'
)";
echo $SQL;
};
The first implementation wont work as your calling a variable rather than the key in your array.
'$employee_first_name.$k',
Should be
$employee_array['employee_first_name'.$k]
You are also creating the SQL statement every iteration of the for loop, so in this implementation only the last employee will save.
Also I don't see the reasoning in doing it that way anyway you may as well just use the employee_data array and the $k variable can also be made redundant.
$SQL = "";
for($n=0; $n<count($employee_data); $n++ ){
$SQL .= "INSERT INTO employee_test (
employee_first_name,
employee_last_name,
employee_birthdate
) VALUES (";
$SQL .= "'".$employee_data[$n]['First']."',";
$SQL .= "'".$employee_data[$n]['Last']."',";
$SQL .= "'".$employee_data[$n]['Birth Date']."'";
$SQL .= ");";
};
Ive not tested but it should give you an idea.
You will also have issues with the date formatted that way, Your database would likely require the date in yyyy/mm/dd format
Finally I would not recommend inserting values like this, look at the PDO library for placeholders.
I think I understand what you're trying to do here. You are using the = operator, effectively setting $SQL to a new value each time your loop iterates. If you adapt your code, you will be able to append to $SQL variable each time.
//I used this array for testing. Comment this out
$employee_data = array(
0 => array(
"first" => "test",
"last" => "tester",
"birth date" => "01/01/1970"
),
1 => array(
"first" => "bob",
"last" => "david",
"birth date" => "02/02/1972"
),
);
//Start SQL as a blank string
$SQL = "";
//Do your iteration
foreach( $employee_data as $key=>$value ){
$first = $value['first'];
$last = $value['last'];
$birthDate = $value['birth date'];
//append this query to the $SQL variable. Note I use `.=` instead of `=`
$SQL .= "INSERT INTO employee_test(
`employee_first_name`,
`employee_last_name`,
`employee_birthdate`)
VALUES(
'$first',
'$last',
'$birthDate'
);";
}
//output the query
echo $SQL;
There are much easier ways of doing this though. Look into prepared statements :)

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

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

Implode error on web crawler

I am on the final strip for a web crawler that I am writing.
The web crawler crawls BBC News and then inserts links into the database along with titles and descriptions etc. all that works but I have an array with all the starting urls, so that only links that begin with any of them are only inserted.
I am using a foreach to loop over all the array variables for the array of all links and checking if they match the criteria, inserting into the new array and then imploding that to a string and then inserting into a mysql database.
An error appears, however, regarding my implode function. I am stuck.
$bbc_values = array('http://www.bbc.co.uk/news/health-', 'http://www.bbc.co.uk/news/politics-', 'http://www.bbc.co.uk/news/uk-', 'http://www.bbc.co.uk/news/technology-', 'http://www.bbc.co.uk/news/world-', 'http://www.bbc.co.uk/news/england-', 'http://www.bbc.co.uk/news/northern_ireland-', 'http://www.bbc.co.uk/news/scotland-', 'http://www.bbc.co.uk/news/wales-', 'http://www.bbc.co.uk/news/business-', 'http://www.bbc.co.uk/news/education-', 'http://www.bbc.co.uk/news/science_and_enviroment-', 'http://www.bbc.co.uk/news/entertainment_and_arts-', 'http://edition.cnn.com/');
foreach ($links as $link) {
$output = array(
"title" => Titles($link), //dont know what Titles is, variable or string?
"description" => getMetas($link),
"keywords" => getKeywords($link),
"link" => $link
);
if (empty($output["description"])) {
$output["description"] = getWord($link);
}
foreach ($output as $new_array) {
if (in_array($new_array['link'], $bbc_values)) {
$news_stories[] = $new_array;
}
}
$data = '"' . implode('" , "', $news_stories) . '"';
$result = mysql_query("INSERT INTO news_story (`title`, `description`, `keywords`, `link`) VALUES (" . $data . ")");
Firstly, $links is not defined. Did you mean $bbc_value ?
Otherwise, you have to close the first foreach (closing } missing)
Inside your foreach loop you have
$news_stories[] = $new_array;
which will produce an array of arrays maybe something like following
array(
array(
'title'=>'title1',
'description'=>'description1',
'keywords'=>'keywords1',
'link'=>'link1'
),
array(
'title'=>'title2',
'description'=>'description2',
'keywords'=>'keywords2',
'link'=>'link2'
)
);
and you are using implode outside of loop like this
$data = '"' . implode('" , "', $news_stories) . '"';
which should not work unless you specify an index in the array. So, if you use following code
$data='"' . implode('" , "', $news_stories[0]) . '"';
echo $data;
then it'll implode first array item from the $news_stories array and it'll produce following
"title1" , "description1" , "keywords1" , "link1"
If you want to produce following
$result = mysql_query("INSERT INTO news_story (`title`, `description`, `keywords`, `link`) VALUES ('title1' , 'description1' , 'keywords1' , 'link1')");
then you can use
$data="'" . implode("' , '", $news_stories[0]) . "'";
so if you write
$result = mysql_query("INSERT INTO news_story (`title`, `description`, `keywords`, `link`) VALUES (" . $data . ")");
then it'll out produce
$result = mysql_query("INSERT INTO news_story (`title`, `description`, `keywords`, `link`) VALUES ('title1' , 'description1' , 'keywords1' , 'link1')");

insert value array in database and next get(each) part of it?

I use of codeigniter. how can insert several value (array) <input name="ok[]"> in database and get they of database. (what is the best way?)
type rows in database is "VARCHAR" and "utf-8".
<input type="text" name="ok[]">
Values: (This is just one example of what I want)
ok[1] => hi, how are you?, 5426, assd, 54568
ok[2] => what, your name?, 548568a, 684a45ade
ok[3] => asdwhasdat, fine, 85as454se, 4e748sd
ok[3] => 85as454se, George, asdwhasdat, 4e748sd
Etc. ....
Now after it, i want inputs ok[1], ok[2], ok[3] together insert in a row (column) on database.
NEXT:
I want get (the second part) they of database and each they in foreach as:
how are you? fine your name? George
how is it?
$inserts = array();
foreach ($_REQUEST['ok'] as $key => $val)
{
$parts = explode(',', $val);
$inserts[] = "('" . mysql_real_escape_string($parts[1]) . "')";
}
$inserts = implode(',', $inserts);
$sql = "INSERT INTO yourtable (fieldname) VALUES $inserts;";
$result = mysql_query($sql) or die(mysql_error());

Categories