"writing a pdo search query from a php array" Code Answer

3

here`s a simple solution to your problem:

$sql = 'select ..... from ... where 1 ';
$where = '';
$pdodata = [];

foreach ($search_data as $key => $value) {
    if(!$value) continue; // skip empty values

    if ($key === 'category') {
        $pdodata[':category'] = $value;
        $where .= ' and category = :category ';
    }
    if ($key === 'course_name') {
        $pdodata[':course_name'] = '%'.$value.'%';
        $where .= ' and course_name like (:course_name) ';
    }
    if ($key === 'date') {
        $pdodata[':date'] = $value;
        $where .= ' and date = :date ';
    }
}

$sql = $sql.$where;

$stmt = $this->ci->db->prepare($sql);
$stmt->execute($pdodata);
$results = $stmt->fetchall(pdo::fetch_assoc);

and you have $pdodate array holding the binded data.

By krillgar on May 3 2022

Answers related to “writing a pdo search query from a php array”

Only authorized users can answer the Search term. Please sign in first, or register a free account.