Search code examples
phppdoappendexecute

PDO prepare/execute the table and append WHERE's


I'm trying to do the following:

public function checkResult($table, $appends)
{
    $append = null;
    foreach ($appends as $key => $val)
        $append = " AND `{$key}` = '{$val}'";

    $result = $this->fetchObj("
        SELECT  *
        FROM    :cms_table
        WHERE   id :append
    ", array(
        ":cms_table" => $table
        ":append" => $append
    ));

    return ($result ? true : false);
}

But I can't get this working because I don't know how to do this in PDO.
Also when I leave the :append my query isn't working either. It looks like I can't execute a table. When I change :cms_table to the cms_pages (table I need) it works correctly.

I couldn't find a thing about such query's in PDO. Anyone who can help me out?


Solution

  • Don't try to outsmart yourself.

    You don't need no checkResult() function, as well as no other function of similar structure.

    $sql   = "SELECT 1 FROM table WHERE field = ? AND col = ?";
    $found = $db->fetchObj($sql, array(1,2));
    

    is all you actually need.