Skip to content

Instantly share code, notes, and snippets.

@remoharsono
Last active September 28, 2016 08:27
Show Gist options
  • Save remoharsono/4342989 to your computer and use it in GitHub Desktop.
Save remoharsono/4342989 to your computer and use it in GitHub Desktop.
Inserting data with Implode to MySQL
<?php
// source: http://stackoverflow.com/questions/779986/insert-multiple-rows-via-a-php-array-into-mysql
$sql = array();
foreach( $data as $row ) {
$sql[] = '("' . mysql_real_escape_string($row['text']) . '", ' . $row['category_id'] . ')';
}
mysql_query('INSERT INTO table (text, category) VALUES ' . implode(',', $sql));
?>
@onwu
Copy link

onwu commented Sep 28, 2016

good evening, i tried ur code and i got stuck somewhere. this is the error i get

Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\new\save_sal.php on line 15

`<?php
if (isset($_POST['submit']))
{
//database connection
include('connection.php');
include('sanitise.php');

$grade_id = sanitise ($_POST['grade_id']);
$id = sanitise ($_POST['id']);
//$submit = ($_POST['submit']);

//record insertion
$sql = array();

foreach($id as $row) {
$sql[] = '("' . sanitise($row['grade_id']) . '", ' . $row['id'] . ')';
}
mysql_query('INSERT INTO tbl_sal (grade_id, id) VALUES ' . implode(',', $sql));

}
?>
and this is the form


    </tr>`

i am fetching the grades from a database table.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment