D
D
DeniSidorenko2020-03-05 10:03:38
PHP
DeniSidorenko, 2020-03-05 10:03:38

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 был отправлен в качестве параметра :


How to specify that it would be possible to pass the names of the product as a parameter, and not sew in its query query

Answer the question

In order to leave comments, you need to log in

3 answer(s)
F
FanatPHP, 2020-03-05
@FanatPHP

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

V
Vladislav, 2020-03-05
@cr1gger

$getTable = $db->getAll('SELECT * from :product', [':product' => 'product']);

https://www.php.net/manual/en/pdo.prepare.php

T
ThunderCat, 2020-03-05
@ThunderCat

$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 question

Ask a Question

731 491 924 answers to any question