@DeniSidorenko

Почему не работает метод Delete?

Подскажите, из-за чего метод Delete не удаляет пользователя (для примера показал и метод get - он работает)?

index.php
#$products = Database::getInstance()->get('products', ['name', '=', 'Macbook PRO']);
Database::getInstance()->delete('products', ['name', '=', 'Danu']);


Database.php
<?php


class Database
{

  private static $instance = null;
  private $pdo, $query, $error = false, $results, $count;


  private function __construct()
  {
    try{
      $this->pdo = new PDO("mysql:host=localhost;dbname=university;", 'mysql', 'mysql');
    }
    catch (PDOException $e){
      echo $e->getMessage();
    }
  }

  public function getInstance(){


    if(!isset(self::$instance)){
      self::$instance = new Database();
    }
    return self::$instance;
  }


  public function query($sql, $params=[]){
    $this->error = false;
    $this->query = $this->pdo->prepare($sql);

    if(count($params)){
      $i = 1;
      foreach($params as $param){

        $this->query->bindValue($i, $param);
        $i++;
      }
    }

    if(!$this->query->execute()){
      $this->error = true;
    }
    else{
      $this->results = $this->query->fetchAll(PDO::FETCH_OBJ);
      $this->count = $this->query->rowCount();
    }
    return $this;

  }

  public function get($table, $where=[]){

    return $this->action('SELECT', $table, $where);
  }

  public function delete($table, $where=[]){

    return $this->action('DELETE', $table, $where);

  }

  public function action($action, $table, $where){
    if(count($where) === 3){

      $operators = ['=', '>', '<', '<=', '>='];
      $field = $where[0];
      $operator = $where[1];
      $value = $where[2];

      if(in_array($operator, $operators)){

        $sql = "{$action} * FROM {$table} WHERE {$field} {$operator} ?";

        if( !$this->query($sql, [$value])->showError() ){
          return $this;
        }
      }

    }
  }



  public function showError()
  {
    return $this->error;
  }

  public function showResult(){
    return $this->results;
  }

  public function count(){


    return $this->count;

  }

}


UPDATE
Насколько я заметил проблема в методе query
$this->query->execute()
возвращает false
  • Вопрос задан
  • 172 просмотра
Решения вопроса 1
0xD34F
@0xD34F
$sql = "{$action} * FROM {$table} WHERE {$field} {$operator} ?";

То есть, вы пытаетесь выполнить DELETE * FROM .... Круто. Не знал, что так можно. Или всё-таки нельзя?
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы