|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2003-06-11 13:54 UTC] wayne-php at waynef dot com
i have created a function i found useful. i am sure there are better ways to doing this and it doesn't do much error checking but you get the idea and how this may be a useful feature...
/**
** this function will take in an array with keyed values
** and place the values into the
** same name columns as the key name.
**
** bool mysql_insert_array(array, table_name)
**
** ie...
**
** $array = array("id" => $id, "md5" => md5($id));
**
** mysql_insert_array($array, "users");
**/
function mysql_insert_array($array, $table) {
$keys = array_keys($array);
for ($index = 0; $index < count($array); $index++) {
if ($index != 0) {
$columns .= ",";
$values .= ",";
}
/** construct the column names from the array **/
$columns .= $keys[$index];
if (is_int($array[$keys[$index]])) {
$values .= $array[$keys[$index]];
} else {
$values .= "'" . mysql_real_escape_string($array[$keys[$index]]) . "'";
}
}
$query = "INSERT INTO `" . $table . "` (" . $columns . ") VALUES (" . $values . ")";
if (($result = mysql_query($query)) == 0)
return(0);
if (mysql_affected_rows() == 1)
return(1);
else
return(0);
}
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Fri Oct 24 21:00:01 2025 UTC |
This is too special and won't work with lot of MySQL specific column types/syntax. MySQL-Syntax: insert into foo (a) values (GeomFromText('point(10 10)')); insert into foo (a,b) values ("1", a+1); How will you realize these queries with your function? Quoting all values doesn't work. Also you would need a lot of additional parameters for insert delayed, priority and duplicate keys.