PDO does not connect to MySQL
I am trying to make a connection to the bank by PDO, but every time I try to make this connection, the message appears:
could not find driver
I went back to find out and I learned that I had to enable PDO in php.ini. Ok, I went there and took the; from where I needed, but even then the message still appears.
My code is this:
<?php
try{
// Faz conexão com banco de daddos
$pdo = new PDO("
mysql:host=localhost;
dbname=servidores;",
"root",
"root");
}catch(PDOException $e){
// Caso ocorra algum erro na conexão com o banco, exibe a mensagem
echo 'Falha ao conectar no banco de dados: '.$e->getMessage();
die;
}
?>
Does anyone know what it can be?
7 answers
The mysql
extension is not installed or you do not have mysql
installed on localhost
.
Create a file info.php
in the root of the webserver, with the function phpinfo();
and then go to localhost/info.php
and look for pdo
, la you see if the driver pdo
for mysql
is installed.
No linux, type in terminal:
php -i | grep drivers
And verify that the driver is enabled. On Debian / Ubuntu based systems the installation is simple, in the terminal type:
//para instalar
sudo apt-get install php5-mysql
//reiniciando o apache
sudo service apache2 restart
It is quite common to occur, especially with people who develop in Windows environment in versions prior to 5.3, version in which there is no need to enable a separate extension for the PDO itself, they enable only the DLL of the PDO (php_pdo.dll) and if they forget to enable the DLL(s) of the PDO-supported DBMS(s) they will be using.
The solution, also simple, is to edit PHP.Ini removing the comment sign (;) from the referring line A, in the case, php_pdo_mysql.dll
When this type of problem occurs what can happen:
- if you are using windows. it may not have the respective dll
- the installed MySQL port is not the default (3306)
- database data is not correct
A quick and easy way to test if mySQL is available is by PDO itself with its function PDO:: getAvailableDrivers()
$drivers = PDO::getAvailableDrivers();
foreach ($drivers as $nome) {
echo 'Disponivel: ' . $nome . '<br />';
}
In this way you list all the drivers that PDO can use.
Run php -m
in the terminal/prompt and check if the pdo_mysql extension is actually enabled, if it is and still not working check if MySQL has started.
That's how it works.
try{
// Faz conexão com banco de daddos
$host = ('localhost');
$user = ('root');
$pass = ('root');
$bancodb = ('curso_php');
$conecta = new PDO("mysql:host=$host;dbname=$bancodb", $user, $pass);
}catch(PDOException $e){
// Caso ocorra algum erro na conexão com o banco, exibe a mensagem
echo 'Falha ao conectar no banco de dados: '.$e->getMessage();
die;
}