The mysql_fetch_assoc "converts" a row from a table into an associative array.
The mysql_insert_array "converts" an associative array into a row in a table.
<?php
function mysql_insert_array ($my_table, $my_array) {
// Version 1.1
// 31.aug..2006 12:41
// Copyright: you may do whatever you wish (and can ;-) ) with this code
// Find all the keys from the array $my_array
$keys = array_keys($my_array);
// Find the number of the keys
$keys_number = count($keys);
// Generate the column name for the $sql query
$column_names = "(";
$values = "(";
// We don't add "," after the last one
if ($i == ($keys_number - 1)) {
$column_names .= "`$keys[$i]`";
$values .= "'$my_array[$column_name]'";
} else {
$column_names .= "`$keys[$i]`" . ", ";
$values .= "'$my_array[$column_name]'" . ", ";
}
}
// Proper end the column name and the value
$column_names .= ")";
$values .= ")";
// We compose the query
$sql = "insert into `$my_table` ";
$sql .= $column_names;
$sql .= ' values ';
$sql .= $values;
$result = mysql_query($sql);
if ($result)
{
echo "The row was added sucessfully";
return true;
}
else
{
echo ("The row was not added<br>The error was" . mysql_error());
return false;
}
}
?>
Below you'll find an example:
<?php
// Establish the connection with the database
require_once ("dbconnect.php");
// The database has one table, called `test`, created as following:
// CREATE TABLE `test`
// (
// `one` varchar(20) default NULL,
// `two` varchar(20) default NULL
// )
// TYPE=MyISAM;
// We create the $test array
$row = array (
"one" => "first",
"two" => "second"
);
// We want to insert the $row into $table
$table = "test";
// We insert the array into the database
mysql_insert_array ($table, $row);
?>