How to verify if connected in the database?

Asked

Viewed 2,365 times

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

  • 1

    Maybe it’ll help: PDO Connection Test

  • 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.

  • I updated the question...

  • What mistake? I don’t understand.

  • You urged the class $conn = new AcessoDados(); first of all? example

3 answers

7

<?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

4

Buddy, 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 that generate if it does not connect! To hide the errors change to 0.

  • I’m accessing http://localhost/Controleservicos/Acessodados/Acessodados.php, but nothing appears on the page.

  • So maybe it’s pq he connected! ";

  • I put before the Try and after, but he echo does not appear, I’m doubting that my code is running.

  • @J.C.Galhardi Only a white screen can say that there is an error that is not being reported before to fall into Try. See the Common Errors section in the [tag:php]

  • I updated the question...

1


Thanks to the comrade’s help Tiago NET I built this script with safety techniques and fully functional for you, I have been perfecting 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"]; } ?>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.