3v4l.org

run code in 150+ php & hhvm versions
Bugs & Features
<?php /** * 安全地执行SQL语句. * * 该函数会将所有参数经过安全地转义, 用来替换SQL命令中的占位符, 最后送至服务器进行执行. * * 占位符是 %s , 如果需要在SQL命令中包含百分号, 请连写两个百分号. * * @param resource $conn 由 mysql_connect() 建立的MySQL数据库连接资源 * @param string $sql SQL语句, 可以包含占位符 * @param mixed $more... 用来替换占位符的参数 * * @return resource 该函数会返回 mysql_query() 的返回值. */ function safeSQL($conn,$sql,$more=NULL) { $args=func_get_args(); array_shift($args); array_shift($args); $offset=0; foreach($args as $i) { if(preg_match("/%([sS])/",$sql,$result,PREG_OFFSET_CAPTURE,$offset)) { $fStr=$result[1][0]; $pos=$result[1][1]; $tPos=$pos-1; while($sql[$pos]=="%") $tPos--; if(!(($pos-$tPos)%2)) continue; $value=strval($i); $sql=substr($sql,0,$pos-1) . $value . substr($sql,$pos+1); $offset=$pos + 1; } } $sql=str_replace("%%", "%", $sql); echo $sql."\n"; } safeSQL(0,"SELECT * FROM `user`"); safeSQL(0,"SELECT * FROM `user` WHERE `uname`='%s'","jybox"); safeSQL(0,"UPDATE `%s` SET `email`='%t' WHERE `uname`='%s'","user","m@jybox.net","jybox"); safeSQL(0,"SELECT * FROM `user` WHERE `uname` LIKE ='%%%s%%'","jybox"); safeSQL(0,"SELECT * FROM `user`");
Output for 4.3.3 - 5.6.28, hhvm-3.10.0 - 3.12.0, 7.0.0 - 7.1.0
SELECT * FROM `user` SELECT * FROM `user` WHERE `uname`='jybox' UPDATE `user` SET `email`='%t' WHERE `uname`='m@jybox.net' SELECT * FROM `user` WHERE `uname` LIKE ='%jybox%' SELECT * FROM `user`
Output for 4.3.0 - 4.3.2
SELECT * FROM `user` Warning: Wrong parameter count for preg_match() in /in/N7o5P on line 25 SELECT * FROM `user` WHERE `uname`='%s' Warning: Wrong parameter count for preg_match() in /in/N7o5P on line 25 Warning: Wrong parameter count for preg_match() in /in/N7o5P on line 25 Warning: Wrong parameter count for preg_match() in /in/N7o5P on line 25 UPDATE `%s` SET `email`='%t' WHERE `uname`='%s' Warning: Wrong parameter count for preg_match() in /in/N7o5P on line 25 SELECT * FROM `user` WHERE `uname` LIKE ='%%s%' SELECT * FROM `user`