Why won't this Array Insert into my MYSQL table? [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How show Multidimensional Arrays be inserted into a MySQL table?
I have an array. The array is multidimensional and works fine in regards to being imploded. Then when I make an attempt in order to insert the array into the database, each multidimensional array, per row. It won't go in. Only the final row inserts itself, but after trying this new code, which doesn't insert anything, I am stuck. By the way, I have lost the previous code:
foreach ($links as $link) {
$output = array(
"title" => Titles($link),
"link" => $link,
"description" => getMetas($link),
"keywords" => getKeywords($link)
);
if (empty($output["description"])) {
$output["description"] = getWord($link);
}
$data[] = '"' . implode('" , "', $output) . '"';
}
mysql_query( "INSERT INTO search (title, description , keywords, link)
VALUES (" . $data . ")" );

Because you are assigning the result of implode to $data[], i.e. the next available array element of $data. In this case, you want to assign the result of implode to just $data.
If you print the generated SQL, you would probably just get INSERT INTO ...... VALUES(Array).

the query mysql_query( "INSERT INTO search (title, description , keywords, link)
VALUES (" . $data . ")" ); needs to be inside the foreach loop.
foreach ($links as $link) {
$output = array(
"title" => Titles($link), //dont know what Titles is, variable or string?
"link" => $link,
"description" => getMetas($link),
"keywords" => getKeywords($link)
);
if (empty($output["description"])) {
$output["description"] = getWord($link);
}
$data = '"' . implode('" , "', $output) . '"';
$success = mysql_query( "INSERT INTO search (title, description , keywords, link)
VALUES (" . $data . ")" );
if( $success)
echo $link . ' row inserted';
}

Your INPUT syntax only populates one row.
To add all the rows in one MYSQL query you would change the code as follows:
$data = "";
foreach ($links as $link) {
$output = array(
"title" => Titles($link),
"link" => $link,
"description" => getMetas($link),
"keywords" => getKeywords($link)
);
if (empty($output["description"])) {
$output["description"] = getWord($link);
}
$data .= '("' . implode('", "', $output) . '"), '; // add each row in parenthesis.
}
mysql_query( "INSERT INTO search (title, description , keywords, link)
VALUES " . $data );
Also, your mysql code has all been deprecated, and you should convert over to mysqli as soon as you can.

Related

How can I efficiently insert multiple form values into my MySQL table?

I have a long list of form values that I need to insert into my database. Rather than having a long list of bulky conditionals, is there an efficient way to insert all of these values into separate columns in my database?
Here's my code:
PHP:
// I've removed most of them to simplify demonstration
$title = isset($_POST['title']) ? $_POST['title'] : "";
$name = isset($_POST['name']) ? $_POST['name'] : "";
$description = isset($_POST['description']) ? $_POST['description'] : "";
$how_hear = isset($_POST['how_hear']) ? $_POST['how_hear'] : "";
// I have to do this for every single form element:
if (!empty($title)) {
DB::query('INSERT INTO `table` (`title`) VALUES (?);', array($title));
}
$usrData = array(
"user" => "hello",
"pass" => "pass1",
"mail" => "test#email.com"
);
$cols = "";
$vals = "";
foreach($usrData as $col => $val) {
$col = mysql_real_escape_string($col);
$val = mysql_real_escape_string($val);
$cols.= "`{$col}`, ";
$vals.= "'{$val}', ";
}
$query = "INSERT INTO `myTable` (". rtrim($cols, ", ") .") VALUES (". rtrim($vals, ", ") .");";
mysql_query($query);
Try like this way
$usrData = array(
array(
"user" => "hello",
"pass" => "pass1",
"mail" => "test#email.com"
),
array(
"user" => "user2",
"pass" => "pass2",
"mail" => "user2#email.com"
)
);
$cols = "";
$bindQuery = "";
$i = 0;
foreach($usrData as $udata) {
$vals = "";
foreach($udata as $col => $val){
$col = mysql_real_escape_string($col);
$val = mysql_real_escape_string($val);
$vals.= "'{$val}', ";
if($i == 0)
$cols.= "`{$col}`, ";
}
$bindQuery.= "(" . rtrim($vals, ", ") . "), ";
$i++;
}
echo $query = "INSERT INTO `myTable` (". rtrim($cols, ", ") .") VALUES ". rtrim($bindQuery, ", ") .";";
mysql_query($query);
Assumptions
Database filed names and form field names are not the same.
All data should be inserted into the same record in the database.
All data should be entered into the database even if one or more fields is blank.
Example Post Data
The code below uses the following example data (as though it were sent from a site by the POST method) when outputting the example query.
$_POST["title"] = "Mr.";
$_POST["name"] = "Joe Bloggs";
$_POST["description"] = "Whatever it is this field is for, presumably some text...";
$_POST["how_hear"] = "google / search engine";
Code
$column_names = array(
// Structure: db-field-name => form-field-name
"title" => "title",
"customer_name" => "name", // Example: Database field name would be "customer_name" and the form field name would be "name"
"content" => "description",
"pointer" => "how_hear"
);
$insert_columns = "";
$insert_values = "";
foreach($column_names as $db_name=>$ws_name){ // Loop through fields specified in $column_names
$value = empty($_POST[$ws_name]) ? '' : $_POST[$ws_name];
$insert_columns .= ", `".$db_name."`"; // Backticks to denote field names
$insert_values .= ", '".$value."'"; // Single quotes to denote values
}
// Generate the query
// substr function removes ", " from start of strings
$insert_query = "INSERT INTO `table_name` (".substr($insert_columns, 2).") VALUES (".substr($insert_values, 2).")";
echo $insert_query; // Show example output
// INSERT INTO `table_name` (`title`, `customer_name`, `content`, `pointer`) VALUES ('Mr.', 'Joe Bloggs', 'Whatever it is this field is for, presumably some text...', 'google / search engine')
Quick Points
Shorthand if statments:
$value = empty($_POST[$ws_name]) ? '' : $_POST[$ws_name];
// Is equivalent to:
if( empty($_POST[$ws_name]) ) {
$value = "";
}
else {
$value = $_POST[$ws_name];
}
The above code doesn't do anything to sanitize the input, so don't forget to sanitize the data etc.
You can add as many fields to the $column_names array as necessary and the order is not relevant.
I've used echo to show the query that the code generates as an example. You would obviously not do this... Instead you would pass the query $insert_query to your database connection. Something like:
DB::query($insert_query);
Of course this might (or rather: would )change depending on how you are connecting to the database...

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

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

Categories