Philadelphia Reflections

The musings of a physician who has served the community for over six decades

Related Topics

No topics are associated with this blog

mysql_insert_assoc

Function to make inserting new rows into a database table easier (and safe because quote_smart logic is included inline)

thanks to R. Bradley @ php.net; I have fixed a number of bugs and added quote_smart functionality

My own contribution to php.net is here: george at georgefisher dot com

<?php
function mysql_insert_assoc ($my_table, $my_array) {
   
//
// Insert values into a MySQL database
// Includes quote_smart code to foil SQL Injection
//
// A call to this function of:
//
//  $val1 = "foobar";
//  $val2 = 495;
//  mysql_insert_assoc("tablename", array(col1=>$val1, col2=>$val2, col3=>"val3", col4=>720));
//
// Sends the following query:
//  INSERT INTO tablename (col1, col2, col3, col4) values ('foobar', 495, 'val3', 720)
//
 
    global $db_link;
    
    // Find all the keys (column names) from the array $my_array
    $columns = array_keys($my_array);

    // Find all the values from the array $my_array
    $values = array_values($my_array);
       
    // quote_smart the values
    $values_number = count($values);
    for ($i = 0; $i < $values_number; $i++)
      {
      $value = $values[$i];
      if (get_magic_quotes_gpc()) { $value = stripslashes($value); }
      if (!is_numeric($value))    { $value = "'" . mysql_real_escape_string($value, $db_link) . "'"; }
      $values[$i] = $value;
      }
         
    // Compose the query
    $sql = "INSERT INTO $my_table ";

    // create comma-separated string of column names, enclosed in parentheses
    $sql .= "(" . implode(", ", $columns) . ")";
    $sql .= " values ";

    // create comma-separated string of values, enclosed in parentheses
    $sql .= "(" . implode(", ", $values) . ")";
       
    $result = @mysql_query ($sql) 
              OR die ("<br />\n<span style=\"color:red\">Query: $sql UNsuccessful :</span> " . mysql_error() . "\n<br />");

    return ($result) ? true : false;
}
?>

mysql_update_assoc is a similar function that updates existing records.

Also thanks to https://centricle.com/tools/html-entities/ for encoding

Originally published: Monday, April 20, 2009; most-recently modified: Monday, June 04, 2012