If you need a better source example/layout goto:
http://nopaste.php-q.net/59720
William Bailey wrote:
Hi All,
After having been talking to lots of people in irc lately who are
haveing problems with SQL injection etc i think that haveing a
*_queryf() function would be really useful to help people esp when it
comes to integers and the id=$id where $id = "1 OR" and name='$name'
where $name = "name' OR" issues for example.
Most of the sprintf formatting would take care of itself but any %s
would automatically have addslashes() applied.
I have a php implementation below for the mysql database.
Let me know what you think or if i have missed anything.
<?php
/*
~ * MySQL queryf() function example.
~ */
define('DEBUG', true);
// usage:
// mysql_queryf($query, $link_identifier = NULL, $arg1, $arg2....$argN);
function mysql_queryf() {
~ $args = func_get_args();
~ if(!isset($args[0]) || !(is_null($args[1]) || is_resource($args[1])
) ){
~ return false;
~ }
~ $formatString = array_shift($args);
~ $linkIdentifier = array_shift($args);
~ $parts = preg_split('/%([
0]|\'.)?-?[0-9]*(\\.[0-9]*)*[%abcdufosxX]/', $formatString, -1,
PREG_SPLIT_OFFSET_CAPTURE);
~ $newString = "";
~ for($i = 0; $i < count($parts); $i++){
~ $start = $parts[$i][1] + strlen($parts[$i][0]);
~ if(isset($parts[$i + 1][1])){
~ $length = $parts[$i + 1][1] - $start;
~ }else{
~ $length = strlen($formatString) - $start;
~ }
~ $formatCode = substr($formatString, $start, $length);
~ $newString .= $parts[$i][0].sprintf($formatCode,
(isset($args[$i]) ? ((substr($formatCode, -1, 1) == 's') ?
addslashes($args[$i]) : $args[$i]) : NULL));
~ }
~ if(DEBUG === true){
~ print("Query is:\n".$newString."\n");
~ }else{
~ if(is_resource($linkIdentifier)){
~ return mysql_query($newString, $linkIdentifier);
~ }else{
~ return mysql_query($newString);
~ }
~ }
}
mysql_queryf('SELECT * FROM blah WHERE id=%d AND name=\'%\'.-34s\' AND
account=\'%0.2f\' AND blah=%06d AND value > \'30%%\'', NULL, '1 OR',
'name\'s');
?>
Output:
Query is:
SELECT * FROM blah WHERE id=1 AND
name='name\'s...........................' AND account='0.00' AND
blah=000000 AND value > '30%'
--
Regards,
William Bailey.
Pro-Net Internet Services Ltd.
http://www.pro-net.co.uk/
--
PHP Database Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php