Answer the question
In order to leave comments, you need to log in
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);
}
}
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;
}
class Model
{
protected $db;
public function __construct()
{
$this->db = App::$db;
}
}
Answer the question
In order to leave comments, you need to log in
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;
...
...
$result = $this->db->query($sql)->fetchAll();
return isset($result[0]) ? $result[0] : null;
...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question