Inserting mySQL info the easy way
Listed In Uncategorized » — Viewing Full TutorialI decided to write this tutorial to show you, how to insert info into a table.
You're probably saying to yourself, "Wait, I already know that!"- well yes, you might.
My method though, is pretty simple (hopefully) and will save you the time of writing the whole query out!
So, take this code:
<?
$time = time();
mysql_query( "INSERT INTO table (name, description, time, key) VALUES ('Dan', 'Boring', '$time', '13')" );
?>
We can make this shorter by making a 'cool' function.
<?
// Build an insert query from an array
function insert_query( $table, $array )
{
if( !is_array( $array ) )
{
return false;
}
foreach( $array as $field => $value )
{
$query1 .= $comma.$field;
$query2 .= $comma."'".$value."'";
$comma = ", ";
}
return mysql_query( "INSERT INTO ".$table." (".$query1.") VALUES (".$query2.");" );
}
?>
Question is- how do I use this?!
Easy!
<?
// The function `insert_query`
// function insert_query( ....
// ...
$array = array(
"Name" => "Dan",
"Description" => "Boring",
"Time" => $time,
"Key" => 13
);
insert_query( "table", $array );
?>
I would explain the code, but I'm in a rush (sorry!) :-p
Any problems, PM moi.
Dan.
