Abstraction Layers
|
|
|
|
<?php
function mysql_insert_array($my_array) {
// Version 1.0
// 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 = "(";
for ($i = 0; $i < $keys_number; $i++) {
$column_name = $keys[$i];
// 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 .= ")";
echo "Values = $values<br>";
// We compose the query
$sql = "insert into `test` ";
$sql .= $column_names;
$sql .= ' values ';
$sql .= $values;
echo $sql;
$result = mysql_query($sql);
if (!$result) {
die ('Invalid query: ' . mysql_error());
}
} ?>
|
|
|
Usage 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
$test = array (
"one" => "first",
"two" => "second"
);
// We insert the array into the database
mysql_insert_array ($test); ?>
|
|
|
Rate This Script
|
|
|
|