PHP Designing Interfaces in PHP Introducing Interfaces Implement MySQL RepositoryInterface

I am not sure how can i bind the paramaters for a php call to the database.

How to bind params.

sqlRepository.php
<?php

class sqlRepository extends PDO implements RepositoryInterface
{
    public function all($db)
    {
        $sql = 'SELECT * from ' . $db;
        $stmt = $this->query($sql);
        return $stmt->fetchAll(PDO::FETCH_OBJ);
    }

    public function find($db, $value, $field = 'id')
    {
        $sql = $this->prepare('SELECT * from ' . $db . ' where ' . $field . '= ' . $value;

        $stmt = $this->query($sql);
        var_dump($stmt);
        //$row = $stmt->fetch(PDO::FETCH_OBJ);
        //var_dump($row);
        //return $row; 
    }
}
Simon Coates
Simon Coates
28,647 Points

I used string concatenation on the table and field and normal binding on the value. I think there are issues with binding on table names (see https://stackoverflow.com/questions/182287/can-php-pdo-statements-accept-the-table-or-column-name-as-parameter )

1 Answer

Henrik Christensen
Henrik Christensen
35,787 Points

Try have a quick look at the docs http://php.net/manual/en/pdostatement.bindparam.php :-)

example

<?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < ? AND colour = ?');
$sth->bindParam(1, $calories, PDO::PARAM_INT);
$sth->bindParam(2, $colour, PDO::PARAM_STR, 12);
$sth->execute();
?>