note 62497 deleted from function.mysql-query by philip
| From: | philip@php.net | Date: | Fri, 04 Sep 2015 19:14:50 +0000 |
| Subject: | note 62497 deleted from function.mysql-query by philip | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-203634@lists.php.net to get a copy of this message | ||
Note Submitter: gconnor at sgi dot com
----
I happily grabbed and used the "mysql_prepare()" function given in the first note above.
All is well.
I made a slight tweak so that I could feed in NULL values without getting an empty string (or 0)
instead.
// mysql_query() wrapper. takes two arguments. first
// is the query with '?' placeholders in it. second argument
// is an array containing the values to substitute in place
// of the placeholders (in order, of course).
// Pass NULL constant in array to get unquoted word NULL
function mysql_prepare ($query, $phs = array()) {
foreach ($phs as $ph) {
if ( isset($ph) ) {
$ph = "'" . mysql_real_escape_string($ph) . "'";
} else {
$ph = "NULL" ;
}
$query = substr_replace(
$query, $ph, strpos($query, '?'), 1
);
}
return mysql_query($query);
}
Sample function call:
// Check to see if all variables are defined
if ( isset($f_hostid,$f_eventid,$f_owner,$f_comment) ) {
// For numeric values, blank means NULL
if ( $f_eventid=="" ) { $f_eventid = NULL ; }
$result = mysql_prepare(
'UPDATE Hosts SET event_id=?, owner=?, comment=? WHERE id=?',
array( $f_eventid,$f_owner,$f_comment, $f_hostid )
);
if (!$result) {
$message = 'Error while updating: ' . mysql_error() .
"<br />\n";
die($message);
}
echo "Update successful. <br />\n" ;
} else {
echo "Missing value. Update failed... check form logic. <br />\n" ;
}