代码之家  ›  专栏  ›  技术社区  ›  The Surrican

这个Mysql助手类有什么问题吗?

  •  0
  • The Surrican  · 技术社区  · 15 年前

    它接受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…)。
    • 你觉得这个功能怎么样?好办法?
    1 回复  |  直到 15 年前
        1
  •  0
  •   Vladislav Rastrusny    15 年前

    我不认为允许一个类操作多个SQL连接是一个好主意。这个类的每个实例都应该只允许使用一个SQL连接。或者,如果您试图实现某种手动负载平衡,则应该从用户的角度透明地使用,可能只允许使用“从”和“主”选项。

    此外,如果查询调度是为了负载平衡而完成的,则需要在类构造函数中打开连接,而不是在查询中延迟打开它们。一个剧本是很短的生物。在查询真正执行之前,不需要延迟连接,除非您为长期操作编写CLI脚本。

    推荐文章