Sponsors

Related Links

MySQL INSERT From A PHP Array

I'm hooked on using CodeIgniter which uses an active record class. This is bad because when I work on a non CodeIgniter project the work is not done for me. This article explains the PHP function I wrote which takes a Associative array and converts it into a mysql INSERT statement.

I just wrote this function and I'm looking for your suggestions. If you have an idea of how I could make this, quicker faster or more user friendly please leave a comment in my comments section.

/**
*  Creates an sql string from an associate array
*  $table in the db table name
*  $array is the array
*  $insert is optional.  allows a user to use an update
*  V1.0
*  Last Updated Oct 4. 2009
**/
function _arrayToSql($table, $array, $insert = "INSERT INTO") {

  //Check if user wants to insert or update
  if ($insert != "UPDATE") {
    $insert = "INSERT INTO";
  }

  $columns = array();
  $data = array();
  
  foreach ( $array as $key => $value) {
    $columns[] = $key;
    if ($value != "") {
      $data[] = "'" . $value . "'";
    } else {
      $data[] = "NULL";
    }
                
    //TODO: ensure no commas are in the values
  }
            
  $cols = implode(",",$columns);
  $values = implode(",",$data);

$sql = <<<EOSQL
  $insert `$table`
  ($cols)
  VALUES
  ($values)
EOSQL;
      return $sql;

}
//End _arrayToSql()

Reference

If you found this article helpful, please share!

Comments

comments powered by Disqus