Answer the question
In order to leave comments, you need to log in
How to change from mysqli to PDO?
Good evening! Help to remake the connection from mysqli to PDO.
I am going through a tutorial about MVC, but it contains a connection to mysqli, since I started with PDO, I want to continue with it. What I tried to do looks very bad, and it does not work as it should.
class DB {
protected $connection;
public function __construct($host, $user, $password, $db_name){
$this->connection = new mysqli($host, $user, $password, $db_name);
if( mysqli_connect_error() ){
throw new Exception('Could not connect to DB');
}
}
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 = array();
while( $row = mysqli_fetch_assoc($result) ){
$data[] = $row;
}
return $data;
}
public function escape($str){
return mysqli_escape_string($this->connection, $str);
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question