Tidbit Tuesday on PHP: Simple MySQL Database Insert Function

This builds on a function I did last week: db_query(). You can send any array straight to a MySQL database and it’ll even check to make sure the column actually exists.  Oh, and it returns the id of the record you just added in case you needed it.

<?php
   function db_array_insert($cfg_array, $table, $array) {
      require_once("dbQuery.function");

      $sql = "show columns from ".$table
      $tableArray = db_query($cfg_array, $sql);
      $inputString = "";

      foreach($tableArray as $key => $value) {
         if (array_key_exists($value[0], $array) && $value[0])
            $inputString .= "'".addslashes($array[$value[0]])."', ";
         else
            $inputString .= "'', ";
      }

      $inputString = substr($inputString, 0, -2);
      $sql = "insert into $table values(".$inputString.")"
      db_query($cfg_array, $sql);

      return mysql_insert_id();
   }

   $insert_array = array(
      "column_1" => "something_1",
      "column_2" => "something_2"
   );

   $cfg_array = array(
      "db_loc" => 'www.databaselocation.com',
      "db_user" => 'some user'
      "db_pass" => 'some password'
      "db_name" => 'database_name_here'
   );

   db_array_insert($cfg_array, "some_table", $insert_array); //and use it.
?>

So what do you think?  Having a problem?  Just let me know in the comments.