note 63232 deleted from function.mysqli-real-escape-string by bjori
| From: | bjori@php.net | Date: | Thu, 16 Mar 2006 16:55:55 +0000 |
| Subject: | note 63232 deleted from function.mysqli-real-escape-string by bjori | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-105939@lists.php.net to get a copy of this message | ||
Note Submitter: PHPManual at EZDispatch dot com
Reason: in docs
----
This is a simple quote_smart function for MySQLi. It will quote & escape any number of strings,
adding commas between them so they can be used in an INSERT, etc. The first parameter must be a
mysqli db connection resource. After that, you can pass any number of strings, OR an array of
strings.
<?php
/**
* Escapes and quotes any number of strings (removes slashes first if magic
* quotes is on), and returns them as one string, comma seperated, and perfect
* for INSERTS etc.
*
* @param Resource $db Database link resource
* @param Strings Any number of arguments to be escaped and added to the returned string
* -OR-
* @param Array An array of strings of arguments to be escaped and added to the returned string
* @return string
*/
function quote_smart($db, $values){
if (!is_array($values)) {
$values = func_get_args();
$db = array_shift($values);
}
foreach($values as &$value){
if (get_magic_quotes_gpc()) {$value = stripslashes($value);}
$value = "'".$db->real_escape_string($value)."'";
}
return implode(',',$values);
}
?>
Use it like this:
<?php
//Make some fake data
$cust_info = array();
$cust_info['name'] = 'Cust Name';
$cust_info['address'] = '123 Some Place';
$cust_info['city'] = 'San Diego';
$cust_info['state'] = 'CA';
$cust_info['zip'] = '99999';
$cust_info['contact'] = 'John Doe';
$cust_info['phone'] = '999-999-9999';
//Create a query
$q = 'INSERT INTO
customer (name, address,
city, state, zip, contact, phone)
VALUES('.quote_smart($db, $cust_info['name'], $cust_info['address'],
$cust_info['city'], $cust_info['state'], $cust_info['zip'],
$cust_info['contact'], $cust_info['phone']).')';
// -OR-
$q = 'INSERT INTO customer (name, address,
city, state, zip, contact, phone)
VALUES('.quote_smart($db, $cust_info).')';
?>
Also, it can be used for a single string:
<?php
$_POST['post_body'] = quote_smart($db, $_POST['post_body']);
$q = "INSERT INTO posts (uid, date_time,
post) VALUES ('{$_SESSION['uid']}',
NOW(),'{$_POST['post_body']}')";
?>