K
K
kai6662021-05-20 22:17:55
PHP
kai666, 2021-05-20 22:17:55

Criticize the code! What gross and non-gross mistakes did he make?

More interested in what I stuck in the PHP part of the code.

https://github.com/kovil1402/positions-list

Many thanks in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
FanatPHP, 2021-05-21
@kai666

Ah here rather nor one almost line normal.

  • exit('Ошибка подключения к базе данных!'); twice stupidity. The user of the site is not interested in reading what is broken - the database or the money for beer has run out. As a programmer, this meaningless phrase is all the more useless for you, it does not say anything about WHAT SPECIFICALLY broke so that you can fix it
  • if ($numRows > 0) {pointless piece of code
  • while ($row = $result->fetch_assoc()) {is replaced by$result->fetch_all(MYSQLI_ASSOC)
  • $this->connect()connect every time to complete the request, seriously?
  • And when there will be another class, for another table, will you write the code for connecting to the database again? And so in everyone?
  • Why is the class for working with "positions" called DBh?
  • In fact, this is not a class, but a set of functions. If you remove the beautiful words class and this, then NOTHING will change
  • SQL injection all around
  • class Handler extends DbhIT IS NOT SURE WHY

In general, something like this
dbh.php
class Dbh
{
    public $conn;

    public function __construct($config)
    {
        mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
        $this->conn = new mysqli(...$config);
        $this->conn->set_charset('utf8mb4');
    }

    public function preparedQuery($sql, $params, $types = '')
    {
        $types = $types ?: str_repeat('s', count($params));
        $stmt = $this->conn->prepare($sql);
        $stmt->bind_param($types, ...$params);
        $stmt->execute();
        return $stmt;
    }

    public function selectResult($sql, $params, $types = '')
    {
        if (!$params) {
            return $this->conn->query($sql);
        }
        return $this->preparedQuery($sql, $params, $types)->get_result();
    }
    public function selectAll($sql, $params = [], $types = '')
    {
        return $this->selectResult($sql, $params, $types)->fetch_all(MYSQLI_ASSOC);
    }
    public function selectAssoc($sql, $params = [], $types = '')
    {
        return $this->selectResult($sql, $params, $types)->fetch_assoc();
    }
    public function selectRow($sql, $params = [], $types = '')
    {
        return $this->selectResult($sql, $params, $types)->fetch_row();
    }
    public function selectCell($sql, $params = [], $types = '')
    {
        $row = $this->selectRow($sql, $params, $types);
        return $row ? $row[0] : false;
    }
}

position.php
class Position
{
    protected $dbh;

    public function __construct(Dbh $dbh)
    {
        $this->dbh = $dbh;
    }
    // Получаем все позциии из БД и возвращаем их в массиве $output если записей больше нуля
    public function getAllPositions()
    {
        return $this->dbh->selectAll('SELECT * FROM positions');
    }
    protected function addPosition($content)
    {
        $count = $this->dbh->selectCell('SELECT count(*) FROM positions');
        if ($count < 10) {
            $this->dbh->preparedQuery("INSERT INTO positions (content) VALUES (?)", [$content]);
        }
    }
    protected function deletePosition($id)
    {
        $this->dbh->preparedQuery("DELETE FROM positions WHERE id = ?", [$id]);
    }
    //Поиск позиций в БД по столбцу content
    protected function searchPosition($content)
    {
        $content = "%$content%";
        return $this->dbh->selectAll('SELECT * FROM positions WHERE content LIKE ?',[$content]);
    }
}

config.php
return [
      'db' => [
          'host' => '127.0.0.1',
          'username' => '',
          'password' => '',
          'dbname' => '',
          'port' => 3306,
      ],
  ];

handler.php
$config = require 'config.php';
$dbh = new Dbh($config['db']);
$position = new Position($dbh);

switch ($_GET['action']) {
    case 'getpositions':
        $output = $position->getAllPositions();
        echo json_encode($output);
        break;
    case 'addposition':
        $content = $_GET['content'];
        $position->addPosition($content);
        break;
    case 'getsearchpositions':
        $content = $_GET['content'];
        $output = $position->searchPosition($content);
        echo json_encode($output);
        break;
    case 'deleteposition':
        $id = $_GET['id'];
        $position->deletePosition($id);
        break;
    default:
        header("HTTP/1.0 400 Bad Request");
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question