Y
Y
Yevhenii K2015-12-11 00:23:16
PHP
Yevhenii K, 2015-12-11 00:23:16

Object of class PDOStatement could not be converted to string in how to fix?

Good afternoon! I'm trying to change the database connection from mysqli to PDO, at this stage I get an error. Help me understand what the problem is.
The error is gone, but the requests are not being fulfilled.
PS Thanks in advance.

class DB {

    protected $connection;

    public function __construct($host, $user, $password, $db_name){
        //$this->connection = new mysqli($host, $user, $password, $db_name);
        $this->connection = new PDO('mysql:dbname=news_db;host=localhost', $user, $password);
        /*if( mysqli_connect_error() ){
            throw new Exception('Could not connect to DB');
        }*/
        try {
            $dbh = $this->connection;
        } catch (PDOException $e) {
            echo 'Подключение не удалось: ' . $e->getMessage();
        }
    }

    public function query($sql){
        if ( !$this->connection ){
            return false;
        }

        $result = $this->connection->query($sql);

        /*if ( mysqli_error($this->connection) ){
            throw new Exception(mysqli_error($this->connection));
        }*/

        if ( is_bool($result) ){
            return $result;
        }

        $data = [];
        /*while( $row = mysqli_fetch_assoc($result) ){
            $data[] = $row;
        }*/
        while ($row = $result->fetchAll(PDO::FETCH_ASSOC)) {
            $data[] = $row;
        }
        return $data;
    }

    public function escape($str) {
        //return mysqli_escape_string($this->connection, $str);
        return $this->connection->quote($str);
    }
}

Request
public function getByAlias($alias){
        $alias = $this->db->escape($alias);
        $sql = "select * from pages where alias = '{$alias}' limit 1";  // ошибка здесь или ранее
        $result = $this->db->query($sql);
        return isset($result[0]) ? $result[0] : null;
    }

Model class, may need
class Model
{

    protected $db;

    public function __construct()
    {
        $this->db = App::$db;
    }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ivan Lissitzky, 2015-12-11
@janson

Well, you probably not only received the text of the error, but also an indication of where it happened.

...
$result = $this->db->query($sql);
return isset($result[0]) ? $result[0] : null;
...

Specifically, the error "Object of class PDOStatement could not be converted to string" occurs here.
In $result you will have a PDOStatement object after executing query(). To get a result from it, you need to execute
Or like this:
...
$result = $this->db->query($sql)->fetchAll();
return isset($result[0]) ? $result[0] : null;
...

S
shagguboy, 2015-12-11
@shagguboy

Can you tell me where it comes from.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question