Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PDO PHP Adding "AND" in BetweenPlaceholders

Tags:

php

mysql

pdo

I would like to add " AND " in between the key and value pair arguments for my sql query but I don't know how. I have tried search the net but unable to find a solution.

       $cdatahome = fetchCategory(array("status"=>"1","home"=>"1")); 

       function fetchCategory(array $conditions){
        $db = Core::getInstance();

            $sql = "SELECT id, title FROM ruj_category WHERE ";

            $params = array();
            foreach ($conditions as $column => $value) {
            if (preg_match('/^[a-z-.]+$/', $column)) {

            $sql .= "$column = ?";
            $params[] = $value;

     }
    }           
            $sql .= " order by title asc";  
            $res = $db->dbh->prepare($sql);
            $res->execute(array_values($params));
                $res = $res->fetchAll(PDO::FETCH_ASSOC);        

            return $res;
like image 309
Claude Grecea Avatar asked Mar 27 '26 05:03

Claude Grecea


2 Answers

$where = array();
foreach ($conditions as $column => $value) {
    if (preg_match('/^[a-z-.]+$/', $column)) {
        $where[] = "$column = ?";
        $params[] = $value;
    }
}
$sql .= implode(' AND ', $where);
like image 65
Valera Leontyev Avatar answered Mar 29 '26 21:03

Valera Leontyev


$cdatahome = fetchCategory(array("status"=>"1","home"=>"1")); 

   function fetchCategory(array $conditions){
    $db = Core::getInstance();

        $sql = "SELECT id, title FROM ruj_category WHERE ";

        $params = array();
        $i = 0;
        foreach ($conditions as $column => $value) {
        if (preg_match('/^[a-z-.]+$/', $column)) {
        if($i != 0){
        $sql .= ' AND ';
        }
        $sql .= "$column = ?";
        $params[] = $value;
        $i++;
 }
}           
        $sql .= " order by title asc";  
        $res = $db->dbh->prepare($sql);
        $res->execute(array_values($params));
            $res = $res->fetchAll(PDO::FETCH_ASSOC);        

        return $res;
like image 32
1321941 Avatar answered Mar 29 '26 19:03

1321941