'php Array map function

I am working on PHP Script and experienced a challenge as a below. My main Aim is to create a Select Query from my db, with different query operators. So far, I have this

public function select(array $columns, array $where)
    {
        $tableName = static::tableName();

        for ($i = 0; $i < count($where); $i++){
            $attributes[] = $where[$i][0];
            $operators[] = $where[$i][1];
        }

        $operator = implode(" ", array_map(fn($oper) => "$oper", $operators));
        $sql = implode(" AND ", array_map(fn($attr) => "$attr $operator :$attr", $attributes));
        $columns = implode(", ", array_map(fn($att) => "$att", $columns));
        $stmt = self::prepare("SELECT $columns FROM $tableName WHERE $sql ");

        .......
    } 

$where contains an array of the Conditions with the column, operator and the value eg [["id", ">", 3], ["firstname", "=", "John"]].

The sql query should be like

SELECT username, email 
FROM table_name WHERE id >  :id AND firstname  = :firstname

However, what I get is

SELECT username, email 
FROM table_name WHERE id >= :id AND firstname >= :firstname

which is incorrect. How can I match the operators correctly?



Solution 1:[1]

I would not use array_map. I would use a foreach and just build the query dynamically:

$where = [["id", ">", 3], ["firstname", "=", "John"]];
$wherequery = ' where ';
foreach($where as $w){
    $wherequery .= $w[0] . ' ' . $w[1] . ' ? ';
    $params[] = $w[2];
}
echo "SELECT columns FROM table " . $wherequery;

then just pass $params to the execute method.

https://3v4l.org/k8F2Y

alternatively with named placeholders:

$where = [["id", ">", 3], ["firstname", "=", "John"]];
$wherequery = ' where';
foreach($where as $w){
    $wherequery .= ' ' . $w[0] . ' ' . $w[1] . ' :' . $w[0];
    $params[$w[0]] = $w[2];
}
echo "SELECT columns FROM table " . $wherequery;

https://3v4l.org/5WXK5

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user3783243