note 90416 added to function.mysql-fetch-assoc
| From: | george at georgefisher dot com | Date: | Tue, 21 Apr 2009 14:51:35 +0000 |
| Subject: | note 90416 added to function.mysql-fetch-assoc | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-153545@lists.php.net to get a copy of this message | ||
Thanks to to R. Bradley for the implode idea. The following fixes a few bugs and includes
quote_smart functionality (and has been tested)
<?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, col5=>834.987));
//
// Sends the following query:
// INSERT INTO 'tablename' (col1, col2, col3, col4, col5) values ('foobar',
495, 'val3', 720, 834.987)
//
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;
}
?>
----
Server IP: 208.69.120.35
Probable Submitter: 207.172.78.142
----
Manual Page -- http://www.php.net/manual/en/function.mysql-fetch-assoc.php
Edit -- https://master.php.net/note/edit/90416
Del: integrated -- https://master.php.net/note/delete/90416/integrated
Del: useless -- https://master.php.net/note/delete/90416/useless
Del: bad code -- https://master.php.net/note/delete/90416/bad+code
Del: spam -- https://master.php.net/note/delete/90416/spam
Del: non-english -- https://master.php.net/note/delete/90416/non-english
Del: in docs -- https://master.php.net/note/delete/90416/in+docs
Del: other reasons-- https://master.php.net/note/delete/90416
Reject -- https://master.php.net/note/reject/90416
Search -- https://master.php.net/manage/user-notes.php