Hi, Guest ~ Login or Register

Inserting mySQL info the easy way

Inserting mySQL info the easy way

Listed In Uncategorized » — Viewing Full Tutorial
Hey guys,

I 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.





Working Beta

  1. The Forums
    These are mostly functional. If you see any weird bugs, post a thread about it and an administrator will do something.
  2. Tutorial Writing
    You can now submit tutorials to the brand new management system.
  3. Tutorials Home
    View tutorials by categories and search for them here.
  4. Shoutbox
    See below. Registered users only!

Register

Newest User

Say hi to kapricon! kapricon joined on Wednesday, 24th December.

Sponsor

Shoutbox