0

The prepared statements and pdo are new for me.

I have now the Insert en select with prepared statements in one class

 public function query($string, $parameters = null)
{
    try {
        $statement = $this->pdo->prepare($string);
        $statement->execute($parameters);
        $this->rowCount = $statement->rowCount();
        return $statement->fetchAll(PDO::FETCH_OBJ);
    } catch (PDOException $e) {
        // Show nice message
        return $e->getMessage();
    }
}
public function selectAll($table)
{
    return $this->query("SELECT * FROM `${table}`");
}
public function select($table, ...$fields)
{
    $sql = sprintf(
        "SELECT %s FROM `%s`",
        implode(', ', $fields),
        $table
    );
    return $this->query($sql);
}
public function insert($table, $parameters)
{
    $sql = sprintf(
        "INSERT INTO %s (%s) VALUES (%s)",
        $table,
        implode(', ', array_keys($parameters)),
        ':' . implode(', :', array_keys($parameters))
    );
    return $this->query($sql, $parameters);
}

I saw on the internet much examples but with no flexible amount of columns and their values I need that its flexible because i have some controllers with update things that have all diffrent amount of colmns in the database.

Can someone tell me how to make a Function for my database class with a update query with flexible prepared statements?

  • Please read my article, [Common mistakes in Database Wrappers](https://phpdelusions.net/pdo/common_mistakes), you may find it useful. Your class is prone to almost every issue – Your Common Sense Oct 27 '17 at 13:58
  • You're not really running your queries with bound parameters since you're just plugging the parameters directly into the query. In your query, you should use placeholders and pass the parameters in an array. For example, for your selectAll function, you should have `$query="SELECT * FROM :tbl";`, and you should call `$this->query($query,array("tbl"=>$table);` – syndicate_software Oct 27 '17 at 13:58
  • @syndicate_software it won't work with table names – Your Common Sense Oct 27 '17 at 13:59
  • Oh, I didn't realize that. That was just the simplest one to use to show an example. – syndicate_software Oct 27 '17 at 14:04

0 Answers0