13
how do I check my code PHP + PDO successfully connected to the database Mysql?
With code like this it works:
<?php
/* Connect to a MySQL database using driver invocation */
$dsn = 'mysql:host=localhost;port=3306;dbname=bancoservico';
$user = 'root';
$password = '';
$opcoes = array( PDO::ATTR_PERSISTENT => true,
PDO::ATTR_CASE => PDO::CASE_UPPER
);
try {
$dbh = new PDO($dsn, $user, $password, $opcoes);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
The error occurs when the code is like this:
<?php
class AcessoDados {
public function __construct(){
$dsn = 'mysql:host=localhost;port=3306;dbname=bancoservico';
$user = 'root';
$password = '';
$opcoes = array( PDO::ATTR_PERSISTENT => true,
PDO::ATTR_CASE => PDO::CASE_UPPER
);
try {
$dbh = new PDO($dsn, $user, $password, $opcoes);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
}
}
Link to test: http://sandbox.onlinephpfunctions.com/code/4382d8813f699766f41658ce9f3101867eb8fd36
Maybe it’ll help: PDO Connection Test
– Florida
The way is to create the connection as it is in the documentation (http://php.net/manual/en/class.pdo.php) and at the end gives an echo in the variable that stores the connection , in the documentation it says that if it successfully occurs the variable will return a PDO object. Try it this way.
– Marlysson
I updated the question...
– user31040
What mistake? I don’t understand.
– rray
You urged the class
$conn = new AcessoDados();
first of all? example– Ivan Ferrer