문제

Okay I have a function called sendQuery which sends your query. I know how to do it with BindParams, but I can't really think of a way to make it work with bind values inside a execute.

This is the code:

    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();
        }
    }

As you see, it executes with $binds,

Works like (WHERE user = ?), but I want to send queries like this: (WHERE user = :user) instead of a ' ? ', and multiple of them.

How do I do so?

도움이 되었습니까?

해결책

You have to do exactly the same.
Just get rid of useless code and use consistent variable naming

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);

However, instead of just single function I would create a set of them:

  • query() to run non-select queries
  • getOne() preforms select and returns scalar value
  • getRow() returns a row
  • getAll returns all rows

it could be extremely handy

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top