Answer the question
In order to leave comments, you need to log in
What is the correct way to pass parameters to an OOP PDO query?
hello there is a method
// Get All Rows
public function getAll($query, $params=[]){
try{
$stmt = $this->datab->prepare($query); // Подгатавливаем запрос, указывая $table как переменную
$stmt->execute($params); // Выполняем запрос
return $stmt->fetchAll(); // Поулчаем результаты
} catch(PDOException $e) {
throw new Exception($e->getMessage()); // Вывод ошибки если не удалось подключиться к базе данных
}
}
$db = new Database();
// $getTable = $db->getAll('SELECT * from ?', ['product']); -- Выдает ошибку что неверный запрос в базе данных :(
$getTable = $db->getAll('SELECT * from product'); // Не получает задать что бы product был отправлен в качестве параметра :
Answer the question
In order to leave comments, you need to log in
Within the limits of the given method - in any way .
To substitute the name of the table in the query, you will need to really learn OOP, and write real classes, and not what you have now - an ordinary function, which in fact does not need a class.
If no one is going to read the question and write a normal answer, I'll try to find time over the weekend and finish an article that explains how to do it right
$getTable = $db->getAll('SELECT * from :product', [':product' => 'product']);
$params = ['table'=>'product'];
$sql = 'SELECT * from :table';
$getTable = $db->getAll($sql,$params);
Although, in general, this is kind of an internal method of the model, so it must itself substitute the model table from the model properties.
UPD: Thanks to FanatPHP for opening my eyes to my cant, I answered automatically, forgetting that tabnames are not bound. Once again I repeat that the table name is taken from the model (unless, of course, it is ActiveRecord). Accordingly, there will be something like $sql = "SELECT * from `{$this->tableName}`";
, although this is an oversimplification.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question