Insert php nested array into mysql table - php

what is the optimal way for me to insert and array of 1000 lines and 10 columns each into a mysql table below is how i display it so it would be a similar construct but i need some directions
foreach ($stack as $val) {
print "<tr>\n";
foreach ($val as $no) {
print " <td>$no</td>\n";}
print "</tr>\n";
}

You can insert multiple rows with a single insert as follows :
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
look at implode() to create the values string from your array

Better way to insert thousands of data into DB is to use implode function implode

i'm guessing u got something like this
$stack = array("man1" => array("name"=>"ik", "class"=>"highskl", "age"=> "12"),"man1" => array("name"=>"ijk", "class"=>"higkl", "age"=> "13"));
and you want to insert them into a table, try and use the table fields as index for the inner arrays then adjust the code to look like this
foreach ($stack as $entry => $value) {
$query = "INSERT INTO table set ";
foreach ($value as $key => $val) {
$query .= $key ."= ".$val.",";}
//use a string function to remove the last comma
$result = mysql_query($query) or die("Error in Query ".$entry." ",mysql_error());
//this helps to track error..
}

Related

list_columns() multiple table?

title says, is there a way to select column name from multiple table?
DB::list_columns('table1'); //returns columns of table1
what I want to do is
DB::list_columns('table1', 'table2');
I want to select all columns of 2 or more tables.
is it possible?
Use DB::list_tables() in foreach read the current table using DB::list_columns($current_table)
If you use PDO_Connection, this is not supported.
Thanks for those who replied, here is what I did
$col1 = DB::list_columns('table1');
foreach ($col1 as $key => $value) {
array_push($columns['col1'], $key);
}
$col2 = DB::list_columns('table2');
foreach ($col2 as $key => $value) {
array_push($columns['col2'], $key);
}
$colnames = array_merge($col1, $col2);
#CBroe thanks for giving me idea!

PHP Insert into table not creating new line of data

I'm new to PHP and I'm trying to insert data from a nested array into a database. I'm noticing though that only the last key:value gets put in (seems almost as if everything else before gets overwritten). How do I get a new line of each data so everything gets put in?
$tmpArray = array(array("one" => abc, "two" => def), array("one" => ghi, "two" => jkl));
// Scan through outer loop
foreach ($tmpArray as $innerArray) {
// Scan through inner loop
foreach ($innerArray as $key => $value) {
if ($key === 'one') {
$sql = "INSERT INTO test2 (alpha, beta) VALUES ('$key', '$value')";
}
}
}
For simplicty, all I'm trying to do is to get "one" and "abc" put into alpha and beta. Then have another row of the table input "one" and "ghi". But when I run the code, all I get is "one" and "ghi". When I put an echo statement though, all the correct stuff gets printed. Just don't understand why they aren't getting input into my tables.
What am I doing wrong? Thanks!
$sql = "INSERT INTO test2 (alpha, beta) VALUES ('$key', '$value')";
This line overwrites the contents of the variable $sql every time it is called. You need to concatenate your strings together instead:
$sql = '';
// Scan through outer loop
foreach ($tmpArray as $innerArray) {
// Scan through inner loop
foreach ($innerArray as $key => $value) {
if ($key === 'one') {
$sql .= "INSERT INTO test2 (alpha, beta) VALUES ('$key', '$value'); ";
}
}
}
Still better, as suggested in a comment, would be to simply execute the query directly rather than store it in a variable. Then you don't have to concatenate the strings together, nor do you have to enable multiple statements in a single MSQLI call.

save data to table by serialize and php

i am use serialize to get data from page to another page by ajax like this :-
var txtCoursesNamewith = $('#with').serialize();
and get it on php page like this :-
$txtCoursesNamewith = ($_POST['txtCoursesNamewith']);
$unserializedData = array();
parse_str($txtCoursesNamewith,$unserializedData);
when print this array its like this :-
[txtCoursesNamewith] => Array
(
[0] => qq
[1] => ff
)
i need to insert this array to my table by foreach, i am try like this :-
foreach ($unserializedData as $value => $key )
but it store in database like this " Array ", how can i store (qq,ff) on table.
You can use implode() function.
$txtCoursesName = implode(",", $txtCoursesNamewith);
Then insert $txtCoursesName as a string.
use this
foreach ($unserializedData as $key => $val ) {
//your query insert into table_name(column_name) values ($val)
}
'Array' in dbrow means you are inserting unserialized array.
instead of:
INSERT INTO table (column) VALUES ({$value})
do:
INSERT INTO table (column) VALUES ({serialize($value)})
Iterate the query in loop or construct an array and execute a single insert query
foreach ($_POST['txtCoursesNamewith'] as $key => $val ) {
//your query insert into table_name(column_name) values ($val)
}

Separate mysql_query from foreach validation check php

This is a snippet of my code. I essentially I have a new array I want to insert into tablename, but before I do that I validate the new stat figures against the old ones, confirm they are numeric and insert into a new row.
I realise what I have done, the mysql_query is inside the foreach loop, it inserts 5 rows all the same. I want it to only insert 1 new row.
How Do I take the mysql_query outside the loop yet keep the validation that the foreach loop provides before attempting to insert a new row?
foreach ($statnumber as $element) {
if ($statnumber != $LastWeeksStats && is_numeric($element)) {
mysql_query("INSERT INTO tablename (idproducts, stat1, stat2, stat3, stat4, stat5, superstat1) VALUES('8', '$statnumber[0]', '$statnumber[1]', '$statnumber[2]', '$statnumber[3]', '$statnumber[4]', '$statnumber[5]')") or die(mysql_error());
} else {
echo "'{$element}' is NOT numeric or results same as last week", PHP_EOL;
}}
mysql_close();
I would remove the elements that fail the check from the array then have the mysql statement outside the loop at the end. Use unset but you have to keep track of what keys to unset like this:
foreach ($statnumber as $key => $element) {
if($statnumber != $LastWeeksStats && is_numeric($element)) {
//do nothing because it is valid
} else {
//remove that element from the array
unset($statnumber[$key]);
echo "'{$element}' is NOT numeric or results same as last week", PHP_EOL;
}
}
//now only valid data is in the array and you can use a mysql query
You will have to update the mysql query based on how many elements are actually in the array at the end like so:
foreach($statnumber as $key => $element) {
$keys[] = "stat$key";
$elements[] = "'$element'";
}
$keystring = implode(",",$keys);
$elementstring = implode(",",$elements);
mysql_query("INSERT INTO tablename (idproducts, $keystring, superstat1) VALUES('8', $elementstring)") or die(mysql_error());

PHP Array Explode

I am imploding data inside of an array, called the following:
["Levels_SanctionLevel_array"]=>
string(14) "IR01,IR02,IR03"
I need to explode this data and input each value as a row inside of mysql. Such as
pri_id value
---------------
01 IR01
02 IR02
03 IR04
Now where I am getting stuck is this:
The array listed above could have 1 value, 3 values (right now I am showing three values) or 5 values, and I dont want to input NULL values inside of my database.
Appreciate any guidance anyone can share...
$data = explode(',',$your_string);
foreach ($data AS $value) {
// INSERT INTO DB
}
A simple loop works correctly, but has the drawback of making multiple queries to the database:
$str = "IR01,IR02,IR03";
$vals = explode(',', $str);
foreach ($vals AS $value) {
// insert into database
}
As DB operations are a more significant bottleneck than building a query in PHP, I would opt to generate the SQL code for a single query as follows:
$str = "IR01,IR02,IR03";
$vals = explode(',', $str);
$query = 'INSERT INTO my_data VALUES ';
foreach ($vals as $value) {
$query .= "('', '".$value."'),";
}
$query = rtrim($query, ',');
// insert into database
Why don't you use an iterator over the array to construct the sql query? That way you will only insert as many elements as you have in the array.
Like the answer above. I think we were answering at the same time.
Supposing your major array is $data:
foreach ($data as $values)
{
$value = explode(",", $values);
foreach ($value as $v)
{
$sql = "INSERT INTO table(value) VALUES('$v')";
}
}

Categories