D
D
DiaTM2017-03-24 17:49:01
PHP
DiaTM, 2017-03-24 17:49:01

I'm a beginner, can you explain if I'm using pdo correctly and handling errors?

Good day fellow developers. I used to use mysql then switched to mysqli, when I found out that in php 7 mysqli was removed, I had to deal with pdo.
What will be better?

<?php
  define('HOST_DB', 'localhost');
  define('USER_DB', 'User');
  define('PASS_DB', 'pass');
  define('NAME_DB', 'db');

define('OPTIONS_DB', 'mysql:host=localhost; dbname=name_db; charset=utf8');
  define('USER_DB', 'User');
  define('PASS_DB', 'pass');

<?php
  define('HOST_DB', 'localhost');
  define('USER_DB', 'User');
  define('PASS_DB', 'pass');
  define('NAME_DB', 'db');
        define('CHARSET_DB', 'utf8');

<?php
  class Database{
    public $db;
    public function __construct($host_db, $user_db, $pass_db, $name_db){
                        //Правильно ли передавать параметры констант в переменных?
      try{
        $this -> db = new PDO("mysql:host=$host_db; dbname=$name_db; charset=utf8", $user_db, $pass_db);
      }
      catch(PDOException $error){
                                  //Запись ошибок в log
        exit('Не удалось подключиться к базе данных!');
      }
      return $this -> db;
    }
    public function get_all_db(){
      $sql = "SELECT `articles_id`, `title`, `keywords`, `description` FROM `articles`";
      $result = $this -> db -> query($sql);
      if(!$result){
        return FALSE;
      }
      for($i = 0; $i < count($result); $i++){ // Возвращает 1 пробовал mysql_num_rows норм отрабатывала //$result -> rowCount(); возвращает правильно 12
        $row[] = $result -> fetchAll(PDO::FETCH_ASSOC);
      }
      return $row;
    }
    public function get_one_db(){
      
    }
  }

but creates an additional multidimensional array(
$result -> rowCount()
if(!$result){
        return FALSE;
      }
      for($i = 0; $i < $result -> rowCount(); $i++){
        $row[] = $result -> fetchAll(PDO::FETCH_ASSOC);
      }
      return $row;
Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [articles_id] => 1
                    [title] => Как правильно использовать теги div, section и article.
                    [keywords] => 
                    [description] => 
                )

            [1] => Array
                (
                    [articles_id] => 2
                    [title] => Валидность HTML-кода
                    [keywords] => 
                    [description] => 
                )

            [2] => Array
                (
                    [articles_id] => 3
                    [title] => HTML 5 Что нового?
                    [keywords] => 
                    [description] => 
                )

            [3] => Array
                (
                    [articles_id] => 4
                    [title] => CSS
                    [keywords] => 
                    [description] => 
                )

            [4] => Array
                (
                    [articles_id] => 5
                    [title] => Сокрытие элементов на CSS.
                    [keywords] => 
                    [description] => 
                )

            [5] => Array
                (
                    [articles_id] => 6
                    [title] => JavaScript
                    [keywords] => 
                    [description] => 
                )

            [6] => Array
                (
                    [articles_id] => 7
                    [title] => Как визуализировать графики и сделать их интерактивными на JavaScript.
                    [keywords] => 
                    [description] => 
                )

            [7] => Array
                (
                    [articles_id] => 8
                    [title] => PHP
                    [keywords] => 
                    [description] => 
                )

            [8] => Array
                (
                    [articles_id] => 9
                    [title] => Что нового в PHP7.1: генерация случайных чисел.
                    [keywords] => 
                    [description] => 
                )

            [9] => Array
                (
                    [articles_id] => 10
                    [title] => Социальная сеть на PHP: вывод домашней страницы.
                    [keywords] => 
                    [description] => 
                )

            [10] => Array
                (
                    [articles_id] => 11
                    [title] => jQuery
                    [keywords] => 
                    [description] => 
                )

            [11] => Array
                (
                    [articles_id] => 12
                    [title] => Ajax запросы с помощью методов $.post() и $.get().
                    [keywords] => 
                    [description] => 
                )

        )

    [1] => Array
        (
        )

    [2] => Array
        (
        )

    [3] => Array
        (
        )

    [4] => Array
        (
        )

    [5] => Array
        (
        )

    [6] => Array
        (
        )

    [7] => Array
        (
        )

    [8] => Array
        (
        )

    [9] => Array
        (
        )

    [10] => Array
        (
        )

    [11] => Array
        (
        )

)

Whether it is correct if to throw in parameters the following?
<?php
  $host = '127.0.0.1';
    $db   = 'test';
    $user = 'root';
    $pass = '';
    $charset = 'utf8';

    $dsn = "mysql:host=$host;dbname=$db;charset=$charset";
    $opt = [
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES   => false,
    ];
    $pdo = new PDO($dsn, $user, $pass, $opt);

  try {
    $dbh = new PDO($dsn, $user, $password);
  } catch (PDOException $e) {
    die('Подключение не удалось: ' . $e->getMessage());
  }
  
  $stmt = $pdo->query('SELECT name FROM users');
  while ($row = $stmt->fetch())
  {
    echo $row['name'] . "\n";
  }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
FanatPHP, 2017-03-24
@DiaTM

No, everything is wrong here.
In short, then
1. Throw the Database class in the trash.
2. Throw all exit() in the code in the trash
3. All try..catch there
As a result, we will have

class article {
    public function __construct($pdo)
        $this->pdo = $pdo;
    }
    public function get_all_db() {
        $sql = "SELECT `articles_id`, `title`, `keywords`, `description` FROM `articles`";
        return $this->pdo->query($sql)->fetchAll();
    }
    public function get_one_db($id){
        $sql = "SELECT `articles_id`, `title`, `keywords`, `description` FROM `articles` WHERE articles_id = ?";
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute([$id]);
        return $stmt->fetch();
    }
}

Everything is convenient, compact and safe.
There is less code than in mysqli and mysql combined.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question