【发布时间】:2025-12-22 05:05:12
【问题描述】:
我的数据库类中有这个函数。 它接受 3 个参数:
- 查询
- 执行它的服务器由存储在配置中的名称标识
- 在 sql 查询中引用的参数数组
示例调用:
$toplist = MyDbClass->q('SELECT * FROM movies WHERE score > ?','slaveserver1',array(100));
代码来了...
/*
* @param the sql query. may be pure sql or having ? as placeholders for variables that are passed in the 3rd param, not enquoted
* @param name of the link (slave or master server or other arbitrary database)
* @param optional array of vars that will be filled in where the ? signs in the query are
*/
public function q($sql,$name,$vars=false) {
// lets see if the link to the server with name $name has already been initialised, if not lets do it
if(!isset($this->links[$name])) {
$this->initialize($name);
}
// if variables have been passed, lets fill them into the query
if($vars !== false) {
// first real scape them all according to the correct link
for($i=0;$i<count($vars);$i++) {
$vars[$i] = mysql_real_escape_string($vars[$i],$this->links[$name]);
}
// now escape all actual % signs so they are not used as placeholders vor vsprintf
$sql = str_replace('%','%%', $sql);
// no add '' quotes arround every placeholder and fill in
$sql = str_replace('?','\'%\'', $sql);
$sql = vsprintf($sql,$args);
}
// now execute the parsed query on the correct server
return mysql_query($sql,$this->links[$name]) or die(mysql_error($this->links[$name]));
}
现在我的问题是:
我的代码有问题吗?特别是:
- 在任何情况下,在查询中将
''引号括在参数周围会使其不起作用? - 是否有一些优雅的方法可以防止我的函数在我的查询中出现像
where score > ''100 ''这样的双引号内容(如果我已经在输入查询中放置了qutoes...)。 - 你觉得这个函数怎么样?这样做的好方法吗?
【问题讨论】: