How to check if you have connected to the database?

12

How do I check if my PHP + PDO code successfully connected to the MySQL database?

With the code 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 looks 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: link

    
asked by anonymous 24.09.2016 / 20:14

3 answers

1

Thanks to comrade's help Tiago NET I've assembled this script with security techniques and fully functional for you, I have improved the way I connect to my database from time to time and today I find it interesting to use this way and now with the help update mentioned.

<?php class query_sql {
    protected static $conect;
    private function __construct() {

        $mysql_host = "";
        $mysql_base = "";
        $mysql_user = "";
        $mysql_pass = "";

        try { self::$conect = new PDO("mysql:host=" . $mysql_host . "; dbname=" . $mysql_base, $mysql_user, $mysql_pass);
            self::$conect -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            self::$conect -> exec("set names utf8");
            $conect = null; }

        catch(PDOException $error) {
            echo $error -> getMessage(); } }

    public static function conect_sql() {
        if (!self::$conect) {
            new query_sql; }
        return self::$conect; } }

    $bind_sql = query_sql::conect_sql(); ?>

<?php $list_information = $bind_sql -> prepare("SELECT user_email, user_name FROM usuarios WHERE user_email = :user_email LIMIT 1");
    $list_information -> bindValue(":user_email", "@");
    $list_information -> execute();
    $list_information = $list_information -> fetchAll(); ?>

<?php foreach($list_information as $list_information) {
    echo $list_information["user_email"] . " | " . $list_information["user_name"]; } ?>

<?php $compare_information = $bind_sql -> prepare("SELECT user_email, user_pass FROM usuarios WHERE user_email = :user_email AND user_pass = :user_pass LIMIT 1");
    $statement_array = array(":user_email" => "@", ":user_pass" => "pass");
    foreach($statement_array as $array_key => $array_value) {
        $compare_information -> bindValue($array_key, $array_value); }
    $compare_information -> execute();
    $compare_information = $compare_information -> fetchAll(); ?>

<?php foreach($compare_information as $compare_information) {
    echo $compare_information["user_email"]; } ?>
    
28.09.2016 / 10:33
6
<?php

class Acesso{
    protected static $db; 
    private function __construct(){
    $db_host = "<nome do host>";
    $db_database = "<nome do banco de dados>";
    $db_usuario = "<nome do usuario>";
    $db_senha = "<senha do usuario>";
    $db_driver = "mysql";

        try{
            self::$db = new PDO("$db_driver:host=$db_host; dbname=$db_database", $db_usuario, $db_senha);
            # Permite ao PDO lançar exceções durante erros.
            self::$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            # Dados armazenados com codificação UTF-8 caso deseje assim
            self::$db->exec('SET NAMES utf8');
        }
        catch (PDOException $e)
        {            
             # Parar carregamento da página
             die("Connection Error: " . $e->getMessage());
        }
     }

        public static function conexao(){
            if (!self::$db)
            {
                new Acesso;
            }
            return self::$db;
        }
    }
}

Save as pdo.class.php or any other name

To use:

  <?php

  include("pdo.class.php");      

  $pdo = Acesso::conexao();
  $stmt = $pdo->prepare('SELECT * FROM tabela'); -> tabela = nome da tabela
    
27.09.2016 / 17:29
5

Friend, maybe you want something like:

<?php

//hide/show errors
ini_set('display_errors', 1);

class AcessoDados {
public $conn;

public function _construct(){
    $dsn = 'mysql:host=localhost;port=3306;dbname=bancoservico';
    $usuario = 'root';
    $senha = '';
    $opcoes = array( PDO::ATTR_PERSISTENT => true,
                     PDO::ATTR_CASE       => PDO::CASE_UPPER    
        );

    try{
        $this -> conn = new PDO($dsn, $usuario, $senha, $opcoes);
    } catch (PDOException $e){
        die('Não foi possível conectar: ' . mysql_error());
    }        
  }
}

Remembering that you can enable the code:

//hide/show errors
ini_set('display_errors', 1);

where 1 is for you Show the errors they generate if it does not connect! To hide the errors change to 0.

    
25.09.2016 / 06:56