Snippet Name: Opposite of mysql_fetch_assoc
Description: 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.
Comment: (none)
Language: PHP, MYSQL
Highlight Mode: MYSQL
Last Modified: March 02nd, 2009
|
<?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 = "(";
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 .= ")";
// 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;
}
}
?>
Example:
<?php
// Include the function's code
require_once ("mysql_insert_array.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 $row 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);
?>
The dbconnect.php:
<?php
// *************************************************
// SET USER Access
// *************************************************
$hostname = "localhost";
$username = " "; // Change your username
$password = " "; // Change your PASSWORD
$database = " "; // Change your DATABASE's name
// *************************************************
// Database Connection
// *************************************************
$connection = mysql_connect($hostname, $username, $password) or die(mysql_error());
$database = mysql_select_db($database, $connection) or die(mysql_error());
?> |