Quick way to INSERT an array into a table
This is a useful function that I wrote to insert an array into a table in your database.
function insert_array($table, $data) {
$cols = '(';
$values = '(';
foreach ($data as $key=>$value) {
$value = addslashes($value);
$cols .= "$key,";
$values .= "'$value',";
}
$cols = rtrim($cols, ',').')';
$values = rtrim($values, ',').')';
$sql = "INSERT INTO $table $cols VALUES $values";
mysql_query($sql) or die(mysql_error());
return mysql_insert_id();
}
$cols = '(';
$values = '(';
foreach ($data as $key=>$value) {
$value = addslashes($value);
$cols .= "$key,";
$values .= "'$value',";
}
$cols = rtrim($cols, ',').')';
$values = rtrim($values, ',').')';
$sql = "INSERT INTO $table $cols VALUES $values";
mysql_query($sql) or die(mysql_error());
return mysql_insert_id();
}
Here is an example of using this code:
<?php
$arr = array('title' => $_POST['title'], 'product_code' => $_POST['product_code'], 'description' => $_POST['description'], 'price' => $_POST['price']);
$product_id = insert_array("products", $arr);
?>
$arr = array('title' => $_POST['title'], 'product_code' => $_POST['product_code'], 'description' => $_POST['description'], 'price' => $_POST['price']);
$product_id = insert_array("products", $arr);
?>


I am working on a project in C# .NET which will use something similar to this. Instead of the array having the column headings and the values I have arrayLists which contain the values for 1 column and so will have to insert the values by going through the arraylist. Thanks for showing how you did it as it is nice to see the different ways people code different algorithms.
Aaron
;-D