【问题标题】:How make a Dynamic bindValue()?如何制作动态 bindValue()?
【发布时间】:2013-05-02 18:43:15
【问题描述】:

好的,我有一个名为 sendQuery 的函数,它可以发送您的查询。 我知道如何使用 BindParams 来做到这一点,但我真的想不出一种方法来让它与执行中的绑定值一起工作。

这是代码:

    public function sendQuery($query, array $value, $do_fetch)
    {
        $query_process = $this->db->prepare($query);
        if(!$query_process->execute($binds))
        {
            throw new excpetion ("An error has occured!");
        }

        $this->insert = $this->db->lastInsertId();

        $this->row_count = $query_process->rowCount();

        if($fetch == true)
        {
            return $query_process->fetchAll();
        }
    }

如你所见,它使用 $binds 执行,

像 (WHERE user = ?) 一样工作,但我想发送这样的查询: (WHERE user = :user) 而不是 ' ? ',以及其中的多个。

我该怎么做?

【问题讨论】:

    标签: php pdo bindvalue


    【解决方案1】:

    你必须做同样的事情。
    只需摆脱无用代码并使用一致变量命名

    public function sendQuery($query, array $binds, $do_fetch)
    {
        $stm = $this->db->prepare($query);
        $stm->execute($binds);
        $this->insert = $this->db->lastInsertId();
        $this->row_count = $stm->rowCount();
    
        if($do_fetch)
        {
            return $stm->fetchAll();
        }
    }
    
    $sql   = "SELECT * FROM t WHERE c1=:name AND c2=:age";
    $param = array ("name" => $name,"age" => $age);
    $data  = $db->sendQuery($sql, $data, 1);
    

    但是,我会创建一组函数,而不仅仅是单个函数:

    • query() 运行非选择查询
    • getOne() 执行选择并返回标量值
    • getRow() 返回一行
    • getAll 返回所有行

    它可能非常方便

    【讨论】:

      猜你喜欢
      • 2019-07-25
      • 1970-01-01
      • 2019-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-11
      • 2020-12-31
      相关资源
      最近更新 更多