mysql data insertion with foreach loop - php

I was inserting records successfully with this code:
foreach($R as $k=>$v)
{
$test_id = str_replace('rep_result_', '', $k);
if(strstr($k, 'rep_result_'))
{
$content = $v;
$SQL = "INSERT INTO report SET
rep_te_id = '$test_id',
rep_result = '$content',
record_id = '$R[payment_id]',
rep_date = '$dt'";
But now I have two extra fields in my table, remark and nor. So now, for inserting all data I made this code:
foreach($R as $k=>$v)
{
$test_id = str_replace('rep_result_', '', $k);
if(strstr($k, 'rep_result_'))
{
$content = $v;
if(strstr($k, 'remark_'))
{
$remark=$v;
if(strstr($k, 'nor_'))
{
$nor=$v;
$SQL = "INSERT INTO report SET
rep_te_id = '$test_id',
rep_result = '$content',
record_id = '$R[payment_id]',
remark = '**$remark**',
nor = '**$nor**',
rep_date = '$dt'";
I did not get anything in the database. Not everything is ok here. If I use only one if condition then data is being inserted like (rep_result,remark,nor any one).
if(strstr($k, 'remark_'))
$remark=$v;
But when I use all the three condition, nothing is stored. I know I have ifstatement or foreach loop problem.

As others have said, your SQL syntax is fundamentally incorrect (mixing INSERT and UPDATE syntax). A single row insert statement would have a structure like this:
INSERT INTO report (rep_te_id, rep_result, record_id, rep_date )
VALUES ( '$test_id', '$content', '$R[payment_id]', '$dt' )
Do read up on prepared statements, MySQLi and PDO to learn more about performance and efficient use of the database server.
Also, just in a general sense, sending numerous independent SQL statements to the database from within a loop is potentially a huge performance issue. There is communication and connection overhead associated with each one of those calls that has nothing to do with the actual data insertion work that you want to the database server to perform.
MySQL allows you to insert multiple rows with the same statement, so you could build up a single SQL statement in your loop, then send all the inserts in one call to the database.
The syntax to insert multiple rows with one statement looks like:
INSERT INTO report (rep_te_id, rep_result, record_id, rep_date )
VALUES ( '1', 'Row 1 content', '1', '2013-04-15' ),
( '2', 'Row 2 content', '2', '2013-04-15' ),
( '3', 'Row 3 content', '3', '2013-04-15' ),
( '4', 'Row 4 content', '4', '2013-04-15' );
For documentation and more examples, see:
http://dev.mysql.com/doc/refman/5.5/en/insert.html
https://stackoverflow.com/a/6889087/618649
https://stackoverflow.com/a/1307652/618649

Your INSERT query statment has mistakes.
I can't test your code but i assume your condition works here is a sample of mysqli connection and INSERT query.
//opening connection
$mysqli = new mysqli($dbserver, $dblogin, $dbpassword, $dbname);
if (mysqli_connect_errno())
{
printf("Connection failed: %s\n", mysqli_connect_error());
exit();
}
foreach($R as $k=>$v)
{
$test_id = str_replace('rep_result_', '', $k);
if(strstr($k, 'rep_result_'))
{
$content = $v;
if(strstr($k, 'remark_'))
{
$remark=$v;
if(strstr($k, 'nor_'))
{
$nor=$v;
$SQL = "INSERT INTO report (`rep_te_id`, `rep_result`, `record_id`, `remark`, `nor`, `rep_date`) VALUES ('".$test_id."', '".$content."', '".$R['payment_id']."', '".$remark."', '".$nor."', '".$dt."')";
echo $SQL //let's see the query
$mysqli->query($SQL) or die($msqli->error.__LINE__);
}
}
}
}
as you see i placed an echo right after the $SQL statement to see if your condition are matched. If the query will not be printed so yuo have problem with all those if condition

hey buddy your insert query syntax is wrong user correct and learn some sql query syntax
INSERT INTO report (rep_te_id,rep_result,remark,nor,rep_date) VALUES ('$test_id','$content','$R[payment_id]','**$remark**','**$nor**','$dt');

Try implement an else for each of your if condition and try echoing something from their, because look like any of your If condition is not getting satisfied.
I would suggest you to echo $k only from all three else because you will be able to know current value of $k.
also specify else no. in echo so you will be able to get which else got called.

Related

SQL INSERT function with PHP only

edit I changed the code to the suggestion answer, all snippets now updated
currently I am playing around with PHP. Therefore I am trying to build a programm which can execute SQL commands. so, what I am trying is to write some functions which will execute the query. But I came to a point where I coundn't help myself out. My trouble is, for the INSERT INTO command, I want to give an array, containing the Data that shall be inserted but I simply can't figure out how to do this.
Here is what I got and what I think is relevant for this operation
First, the function I want to create
public function actionInsert($data_values = array())
{
$db = $this->openDB();
if ($db) {
$fields = '';
$fields_value = '';
foreach ($data_values as $columnName => $columnValue) {
if ($fields != '') {
$fields .= ',';
$fields_value .= ',';
}
$fields .= $columnName;
$fields_value .= $columnValue;
}
$sqlInsert = 'INSERT INTO ' . $this->tabelle . ' (' . $fields . ') VALUES (' . $fields_value . ')';
$result = $db->query($sqlInsert);
echo $sqlInsert;
if ($result) {
echo "success";
} else {
echo "failed";
}
}
}
and this is how I fil the values
<?php
require_once 'funktionen.php';
$adresse = new \DB\Adressen();
$adresse->actionInsert(array('nachname'=>'hallo', 'vorname'=>'du'));
My result
INSERT INTO adressen (nachname,vorname) VALUES (hallo,du)failed
What I wish to see
success
and of course the freshly insertet values in the database
There are a few things to consider when you are working with relational databases without using PDO:
What is the database that you are using.
It's your decision to choose from MySQL, postgreSQL, SQLite and etc., but different DBs generally have different syntax for inserting and selecting data, as well as other operations. Also, you may need different classes and functions to interact with them.
That being said, did you checkout the official manual of PHP? For example, An overview of a PHP application that needs to interact with a MySQL database.
What is the GOAL you are trying to accomplish?
It's helpful to construct your SQL first before you are messing around with actual codes. Check if your SQL syntax is correct. If you can run your SQL in your database, then you can try to implement your code next.
What's the right way to form an SQL query in your code?
It's okay to mess around in your local development environment, but you should definitely learn how to use prepared statements to prevent possible SQL injection attacks.
Also learn more about arrays in PHP: Arrays in PHP. You can use key-value pairs in a foreach loop:
foreach ($keyed_array as $key => $value) {
//use your key and value here
}
You don't need to construct your query in the loop itself. You are only using the loop to construct the query fields string and VALUES string. Be very careful when you are constructing the VALUES list because your fields can have different types, and you should add double quotes around string field values. And YES, you will go through all these troubles when you are doing things "manually". If you are using query parameters or PDO or any other advanced driver, it could be much easier.
After that, you can just concatenate the values to form your SQL query.
Once you get more familiar with the language itself and the database you are playing with, you'll definitely feel more comfortable. Good luck!
Is this inside of a class? I assume the tabelle property is set correctly.
That said, you should correct the foreach loop, that's not used correctly:
public function actionInsert($data_values) //$data_values should be an array
{
$db = $this->openDB();
if ($db) {
foreach ($data_values as $data){
// $data_values could be a bidimensional array, like
// [
// [field1=> value1, field2 => value2, field3 => value3],
// [field1=> value4, field2 => value5, field3 => value6],
// [field1=> value7, field2 => value8, field3 => value9],
// ]
$fields = Array();
$values = Array();
foreach($data as $key => $value){
array_push($fields,$key);
array_push($values,"'$value'");
}
$sqlInsert = 'INSERT INTO ' . $this->tabelle . ' (' . join(',',$fields) . ') VALUES (' . join(',',$values) . ')';
$result = $db->query($sqlInsert);
echo $sqlInsert;
if ($result) {
echo "success";
} else {
echo "failed";
}
}
}
This is a rather basic approach, in which you cycle through you data and do a query for every row, but it isn't very performant if you have big datasets.
Another approach would be to do everything at once, by mounting the query in the loop and sending it later (note that the starting array is different):
public function actionInsert($data_values) //$data_values should be an array
{
$db = $this->openDB();
if ($db) {
$vals = Array();
foreach ($data_values['values'] as $data){
// $data_values could be an associative array, like
// [
// fields => ['field1','field2','field3'],
// values => [
// [value1,value2,value3],
// [value4,value5,value6],
// [value7,value8,value9]
// ]
// ]
array_push('('.join(',',"'$data'").')',$vals);
}
$sqlInsert = 'INSERT INTO ' . $this->tabelle . ' (' . join(',',$data_values['fields']) . ') VALUES '.join(' , ',$vals);
$result = $db->query($sqlInsert);
echo $sqlInsert;
if ($result) {
echo "success";
} else {
echo "failed";
}
}
By the way dragonthought is right, you should do some kind of sanitizing for good practice even if you don't make it public.
Thanks to #Eagle L's answer, I figured a way that finally works. It is diffrent from what I tryed first, but if anyone having similar troubles, I hope this helps him out.
//get the Values you need to insert as required parameters
public function actionInsert($nachname, $vorname, $plz, $wohnort, $strasse)
{
//database connection
$db = $this->openDB();
if ($db) {
//use a prepared statement
$insert = $db->prepare("INSERT INTO adressen (nachname, vorname, plz, wohnort, strasse) VALUES(?,?,?,?,?)");
//fill the Values
$insert->bind_param('ssiss', $nachname, $vorname, $plz, $wohnort, $strasse);
//but only if every Value is defined to avoid NULL fields in the Database
if ($vorname && $nachname && $plz && $wohnort && $strasse) {
edited
$inserted = $insert->execute(); //added $inserted
//this is still clumsy and user unfriendly but serves my needs
if ($inserted) {//changed $insert->execute() to $inserted
echo 'success';
} else {
echo 'failed' . $inserted->error;
}
}
}
}
and the Function call
<?php
require_once 'funktionen.php';
$adresse = new \DB\Adressen();
$adresse->actionInsert('valueWillBe$nachname', 'valueWillBe$vorname', 'valueWillBe$plz', 'valueWillBe$wohnort', '$valueWillBe$strasse');

issue performing an INSERT statement with mysql_query() PHP

basically I am trying to implement a function in one of my PHP classes that makes an entry into a junction table for a many to many relationship.
This is the method here:
public function setTags($value, $id){
global $db;
$tags = $value;
$query .= "DELETE FROM directorycolumntags
WHERE directorycolumn_id = $id; ";
foreach($tags as $tag){
$query .= "INSERT INTO directorycolumntags (directorycolumn_id, tag_id)
VALUES (".$id.",".$tag.");";
}
mysql_query($query);
}
The SQL is produces works fine, as I've echoed it and manually executed it via phpMyAdmin. However, If I leave it as above, the data is never inserted. Does anyone know why this might be happening?
This is the sql it is generating which works fine when I type it manually in:
DELETE FROM directorycolumntags WHERE directorycolumn_id = 178;
INSERT INTO directorycolumntags (directorycolumn_id, tag_id) VALUES (178,29);
INSERT INTO directorycolumntags (directorycolumn_id, tag_id) VALUES (178,30);
INSERT INTO directorycolumntags (directorycolumn_id, tag_id) VALUES (178,32);
The old, unsafe, deprecated mysql_* extension never supported multiple queries. You could, conceivably do this using the mysql replacement extension: mysqli_*, which has the mysqli_multi_query function.
Personally, I'd not use this approach, though. I'd do what most devs would do: use a prepared statement in a transaction to execute each query safely, and commit the results on success, or rollback on failure:
$db = new PDO(
'mysql:host=127.0.0.1;dbname=db;charset=utf8',
'user',
'pass',
array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
)
);
try
{
$db->beginTransaction();
$stmt = $db->prepare('DELETE FROM tbl WHERE field = :id');
$stmt->execute(array(':id' => $id));
$stmt = $db->prepare('INSERT INTO tbl (field1, field2) VALUES (:field1, :field2)');
foreach ($tags as $tag)
{
$stmt->execute(
array(
':field1' => $id,
':field2' => $tag
)
);
$stmt->closeCursor();//<-- optional for MySQL
}
$db->commit();
}
catch (PDOException $e)
{
$db->rollBack();
echo 'Something went wrong: ', $e->getMessage();
}
Going slightly off-topic: You really ought to consider using type-hints. From your code, it's clear that $values is expected to be an array. A type-hint can ensure that the value being passed is in fact an array. You should also get rid of that ugly global $db;, and instead pass the connection as an argument, too. That's why I'd strongly suggest you change your function's signature from:
public function setTags($value, $id){
To:
public function setTags(PDO $db, array $value, $id)
{
}
That way, debugging gets a lot easier:
$instance->setTags(123, 123);//in your current code will not fail immediately
$instance->setTags($db, [123], 123);//in my suggestion works but...
$instance->setTags([123], null, '');// fails with a message saying argument 1 instance of PDO expected
http://docs.php.net/mysql_query says:
mysql_query() sends a unique query (multiple queries are not supported) to the currently active database on the server that's associated with the specified link_identifier
If you can use mysqli perhaps this interest you: mysqli.multi-query
Executes one or multiple queries which are concatenated by a semicolon.
you can not run multiple quires using mysql_query, try to modify your function like this. It would be better if you use mysqli or pdo instead of mysql because soon it will deprecated and it would not work on newer version of php
public function setTags($value, $id){
global $db;
$tags = $value;
mysql_query("DELETE FROM directorycolumntags WHERE directorycolumn_id = $id");
foreach($tags as $tag){
mysql_query("INSERT into directorycolumntags (directorycolumn_id, tag_id) VALUES (".$id.",".$tag.")");
}
}

insert data from array to DB

I know that this theme is very common, but i'm stuck and can't find an error.
I created an array in PHP:
$dataarray=array("FECHAS" => date("Y-m-d"),"HORAS" => date("H:i:s"),
"RGD" => 0,"RGA" => 0,"FLU" => 0,"DD2" => 0,
"H2O" => 0,"PRES:U" => 0,"U" => 0,"V" => 0,"TS" => 0,
"T1" => 0,"T2" => 0,"H1" => 0,"H2" => 0, "HS" => 0,
"VV1" => 0,"VV2" => 0);
and i've got a table in MYSQL with the same names, but when i try to put data into it, it does nothing.
for($j=0;$j<$variable_para_base;$j++)
{
$keys;
$vars;
foreach($dataarray[$j] as $k=>$v)
{
$keys.= $k.',';
$vars.= $v.",";
}
echo $keys."<br>";
echo $vars."<br>";
mysqli_query($mysqli,'INSERT INTO ff ( .$keys.) VALUES ( .vars. ) ') or die(mysql_error());
unset($keys);
unset($vars);
}
if i do it with die option it does for only once another way my key starts to have strange values in the end of it.
Any ideas, and again sorry for maybe a repeted question. I get access to DB because it doesn't give me any error, though noow i'm doubting :(.
You have syntax promlems in your query.
INSERT INTO ff ( .$keys.) VALUES ( .vars. ) '
change it to
INSERT INTO ff ( '.$keys.') VALUES ( '.$vars.') '
Also you need to add ' to the varialbles inserted as VALUES.
like that:
$vars.= "'".$v."',";
In addition your last variable is also ending with , and it shouldn't be.
So your end result might look something like this:
<?
for($j=0;$j<$variable_para_base;$j++)
{
$keys = array();
$vars = array();
foreach($dataarray[$j] as $k=>$v)
{
$keys[] = $k;
$vars[] = $v;
}
$placeholders = array_fill(0, count($keys), '?'); //used to fill a number of '?' needed to fill later
//here we use the '?' array to be placeholders for the values
$query = "INSERT INTO ff (".implode(', ', $keys).") VALUES (".implode(', ', $placeholders).")"; //implode the arrays and separate by comma
$statement = $mysqli->prepare($query);
$types = array(str_repeat('s', count($vars))); //get the number of parameters and put the 's' to it (used for string values)
$values = array_merge($types, $vars); //merge the arrays (gets you {'s', $value})
call_user_func_array(array($statement, 'bind_param'), $values); //bind the values to the statement
$result = $statement->execute(); //execute.
if($result) {
print "Array inserted, worked like a charm.";
}
else {
print "I failed, sorry...". $mysqli->error();
}
unset($keys);
unset($vars);
}
$statement->close();
?>
This is however untested so test it good.
References you can use:
Stackoverflow question: PHP - MySQL prepared statement to INSERT an array
Stackoverflow question: Best way to INSERT many values in mysqli
Stackoverflow question: Mysqli insert command
You can not insert a array directly to mysql as mysql doesn't understand php data types. Mysql only understands SQL. So to insert this array into a mysql database you have to convert it to an sql statement. This can be done manually or by a library. The output should be an INSERT statement.
Here is a standard mysql insert statement.
INSERT INTO TABLE1(COLUMN1, COLUMN2, ....) VALUES (VALUE1, VALUE2..)
If you have a table with name fbdata with the columns which are presented in the keys of your array you can insert with this small snippet. Here is how your array is converted to this statement.
$columns = implode(", ",array_keys($insData));
$escaped_values = array_map('mysql_real_escape_string', array_values($insData));
$values = implode(", ", $escaped_values);
$sql = "INSERT INTO `fbdata`($columns) VALUES ($values)";
you have error in query try this,
mysqli_query($mysqli,'INSERT INTO ff (' .$keys. ') VALUES (' .$vars. ') ') or die(mysql_error());

Inserting multiple rows in a table using PHP

I am trying to insert multiple rows into MySQL DB using PHP and HTML from. I know basic PHP and searched many examples on different forums and created one script however it doesn't seem working. Can anybody help with this. Here is my script:
include_once 'include.php';
foreach($_POST['vsr'] as $row=>$vsr) {
$vsr=mysql_real_escape_string($vsr);
$ofice=mysql_real_escape_string($_POST['ofice'][$row]);
$date=mysql_real_escape_string($_POST['date'][$row]);
$type=mysql_real_escape_string($_POST['type'][$row]);
$qty=mysql_real_escape_string($_POST['qty'][$row]);
$uprice=mysql_real_escape_string($_POST['uprice'][$row]);
$tprice=mysql_real_escape_string($_POST['tprice'][$row]);
}
$sql .= "INSERT INTO maint_track (`vsr`, `ofice`, `date`, `type`, `qty`, `uprice`,
`tprice`) VALUES ('$vsr','$ofice','$date','$type','$qty','$uprice','$tprice')";
$result = mysql_query($sql, $con);
if (!$result) {
die('Error: ' . mysql_error());
} else {
echo "$row record added";
}
MySQL can insert multiple rows in a single query. I left your code as close as possible to the original. Keep in mind that if you have a lot of data, this could create a large query that could be larger than what MySQL will accept.
include_once 'include.php';
$parts = array();
foreach($_POST['vsr'] as $row=>$vsr) {
$vsr=mysql_real_escape_string($vsr);
$ofice=mysql_real_escape_string($_POST['ofice'][$row]);
$date=mysql_real_escape_string($_POST['date'][$row]);
$type=mysql_real_escape_string($_POST['type'][$row]);
$qty=mysql_real_escape_string($_POST['qty'][$row]);
$uprice=mysql_real_escape_string($_POST['uprice'][$row]);
$tprice=mysql_real_escape_string($_POST['tprice'][$row]);
$parts[] = "('$vsr','$ofice','$date','$type','$qty','$uprice','$tprice')";
}
$sql = "INSERT INTO maint_track (`vsr`, `ofice`, `date`, `type`, `qty`, `uprice`,
`tprice`) VALUES " . implode(', ', $parts);
$result = mysql_query($sql, $con);
Please try this code. Mysql query will not accept multiple insert using php. Since its is a for loop and the values are dynamically changing you can include the sql insert query inside the for each loop. It will insert each rows with the dynamic values. Please check the below code and let me know if you have any concerns
include_once 'include.php';
foreach($_POST['vsr'] as $row=>$vsr) {
$vsr=mysql_real_escape_string($vsr);
$ofice=mysql_real_escape_string($_POST['ofice'][$row]);
$date=mysql_real_escape_string($_POST['date'][$row]);
$type=mysql_real_escape_string($_POST['type'][$row]);
$qty=mysql_real_escape_string($_POST['qty'][$row]);
$uprice=mysql_real_escape_string($_POST['uprice'][$row]);
$tprice=mysql_real_escape_string($_POST['tprice'][$row]);
$sql = "INSERT INTO maint_track (`vsr`, `ofice`, `date`, `type`, `qty`, `uprice`,
`tprice`) VALUES ('$vsr','$ofice','$date','$type','$qty','$uprice','$tprice')";
$result = mysql_query($sql, $con);
if (!$result)
{
die('Error: ' . mysql_error());
}
else
{
echo "$row record added";
}
}
I would prefer a more modern approach that creates one prepared statement and binds parameters, then executes within a loop. This provides stable/secure insert queries and avoids making so many escaping calls.
Code:
// switch procedural connection to object-oriented syntax
$stmt = $con->prepare('INSERT INTO maint_track (`vsr`,`ofice`,`date`,`type`,`qty`,`uprice`,`tprice`)
VALUES (?,?,?,?,?,?,?)'); // use ?s as placeholders to declare where the values will be inserted into the query
$stmt->bind_param("sssssss", $vsr, $ofice, $date, $type, $qty, $uprice, $tprice); // assign the value types and variable names to be used when looping
foreach ($_POST['vsr'] as $rowIndex => $vsr) {
/*
If you want to conditionally abort/disqualify a row...
if (true) {
continue;
}
*/
$ofice = $_POST['ofice'][$rowIndex];
$date = $_POST['date'][$rowIndex];
$type = $_POST['type'][$rowIndex];
$qty = $_POST['qty'][$rowIndex];
$uprice = $_POST['uprice'][$rowIndex];
$tprice = $_POST['tprice'][$rowIndex];
echo "<div>Row# {$rowIndex} " . ($stmt->execute() ? 'added' : 'failed') . "</div>";
}
To deny the insertion of a row, use the conditional continue that is commented in my snippet -- of course, write your logic where true is (anywhere before the execute call inside the loop will work).
To adjust submitted values, overwrite the iterated variables (e.g. $vsr, $ofice, etc) before the execute call.
If you'd like to enjoy greater data type specificity, you can replace s (string) with i (integer) or d (double/float) as required.

php push 2d array into mysql

Hay All,
I cant seem to get my head around this dispite the number to examples i read. Basically I have a 2d array and want to insert it into MySQL. The array contains a few strings.
I cant get the following to work...
$value = addslashes(serialize($temp3));//temp3 is my 2d array, do i need to use keys? (i am not at the moment)
$query = "INSERT INTO table sip (id,keyword,data,flags) VALUES(\"$value\")";
mysql_query($query) or die("Failed Query");
Thanks Guys,
Not sure it's be a full answer to your question, but here at least a couple of possible problems :
You should not use addslashes ; instead, use mysql_real_escape_string
It knows about the things that are specific to your database engine.
In your SQL query, you should not use double-quotes (") arround string-values, but single-quotes (')
In your SQL query, you should have as many fields in the values() section as you have in the list of fields :
Here, you have 4 fields : id,keyword,data,flags
but only one value : VALUES(\"$value\")
You should use mysql_error() to know what was the precise error you've gotten while executing the SQL query
This will help you find out the problems in your queries ;-)
<?php
// let's assume we have a 2D array like this:
$temp3 = array(
array(
'some keywords',
'sme data',
'some flags',
),
array(
'some keywords',
'sme data',
'some flags',
),
array(
//...
),
);
// let's generate an appropriate string for insertion query
$aValues = array();
foreach ($temp3 as $aRow) {
$aValues[] = "'" . implode("','", $aRow) . "'";
}
$sValues = "(" . implode("), (", $aValues) . ")";
// Now the $sValues should be something like this
$sValues = "('some keywords','some data', 'someflags'), ('some keywords','some data', 'someflags'), (...)";
// Now let's INSERT it.
$sQuery = "insert into `my_table` (`keywords`, `data`, `flags`) values $sValues";
mysql_query($sQuery);
As an addition to the useful answers already given, if you have a big table that you need to insert it might not fit in one SQL statement. However, making a separate transaction for each row is also slow. In that case, we can tell MySQL to process multiple statements in one transaction, which will speed up the insertion greatly for big tables (>1000 rows).
An example:
<?php
function dologin() {
$db_username = 'root';
$db_password = 'root';
$db_hostname = 'localhost';
$db_database = 'logex_test';
mysql_connect($db_hostname, $db_username, $db_password);
mysql_select_db($db_database);
}
function doquery($query) {
if (!mysql_query($query)) {
echo $query.'<br><br>';
die(mysql_error());
}
}
function docreate() {
doquery("drop table if exists mytable");
doquery("create table mytable(column1 integer, column2 integer, column3 integer)");
}
function main() {
$temp3 = array(
array('1','2','3',),
array('4','5','6',),
array('7','8','9',),
);
dologin();
docreate();
doquery("start transaction");
foreach($temp3 as $row)
doquery("insert into mytable values('" . implode("','", $row) . "')");
doquery("commit") or die(mysql_error());
}
main();
?>
Try this :
// lets array
$data_array = array(
array('id'=>1,'name'=>'a'),
array('id'=>2,'name'=>'b'),
array('id'=>3,'name'=>'c'),
array('id'=>4,'name'=>'d'),
array('id'=>5,'name'=>'e')
)
;
$temp_array = array_map('implode', $data_array, array('","' ,'","','","','","','","'));
echo $query = 'insert into TABLENAME (COL1, COL2) values( ("'.implode('"),("', $temp_array).'") )';
mysql_query($query);

Categories