Jakub Stanek Jakub Stanek - 4 months ago 7
PHP Question

create a universal function for selecting items from db

Hello im writing a website and i want to make my custom function for selecting items from db but i cant solve my problem, anybody help?

function select($select, $from, $where, $item)
{
global $db;
if ($where != "")
{
$pdoselect = $db->prepare("select :select from :from where :where = :where2");
$pdoselect->bindParam(":select", $select);
$pdoselect->bindParam(":from", $from);
$pdoselect->bindParam(":where", $where);
$pdoselect->bindParam(":where2", $item);
$pdoselect->execute();
foreach ($pdoselect as $return)
{
echo $return[" . $select . "];
}
} else {
$pdoselect = $db->prepare("select :select from :from");
$pdoselect->bindParam(":select", $select);
$pdoselect->bindParam(":from", $from);
$pdoselect->execute();
foreach ($pdoselect as $return)
{
echo $return[" . $select . "];
}
}

}

Answer

You can't use placeholders for table and column names, you'll have to do normal string substitution for those parts of the query. You can use a placeholder for the value you're comparing with in the WHERE clause.

    $pdoselect = $db->prepare("select $select from $from where $where = :value");
    $pdoselect->bindParam(':value', $item);