Claude Grecea Claude Grecea - 7 months ago 11
SQL Question

PDO PHP Adding "AND" in BetweenPlaceholders

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;

Answer
$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;
Comments