Any problem with this Mysql Helper class?
I have this function in my database cl开发者_运维问答ass. It accepts 3 parameters:
- The query
- the server to execute it on which is identified by name that is stored in a config
- an array of arguments that is quoted into the sql query
example call:
$toplist = MyDbClass->q('SELECT * FROM movies WHERE score > ?','slaveserver1',array(100));
here comes the code...
/*
* @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]));
}
Now my questions are:
are there any problem with my code? espacially:
- are there any cases where putting
''
quotes around arguments in a query can make it not working? - is there some elegant way to prevent my function from ending up with double quoted stuff like
where score > ''100 ''
in my queries (if i already put qutoes in the input query...). - what you think of the function? good way to do this?
I do not think, that allowing one class to manipulate several SQL connections is a good idea. Every single instance of this class should be allowed to use only one SQL connection. Or, if you are trying to implement some kind of manual load balancing, this should be used transparently from user with, may be, only "slave" and "master" choices allowed.
Probably, you should separate your queries into "read" and "write" ones because you can "read" from any slave, but should "write" to all of them.
Also, if query dispatching is done for load balancing purposes, you need to open connections in class constructor instead of lazy-opening them in query. One script is a very short-living creature. There is no need to delay connections until query is really executing unless you write CLI script for long-term operations.
精彩评论