Undefined property: PDO::$connect_error

后端 未结 3 1045
孤城傲影
孤城傲影 2021-01-26 08:10

I am trying to use $dbc->connect_error to check if any error occurs while trying to connect to my databease. I always get an error page saying:

相关标签:
3条回答
  • 2021-01-26 08:54

    Here is what your code should be

    <?php
    
    $dsn = 'mysql:host=localhost;dbname=technoglance;charset=utf8';
    $username = 'root';
    $password = 'password';
    $dbc = new PDO($dsn, $username, $password);
    $dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // filtering omitted
    
    if(!empty($main_class)){
        $query = "INSERT INTO products (main_class, brand, model, description, quantity, adding_date, sell_price, buying_price ) VALUES (?,?,?,?,?,?,?,?);";
        $data = [$main_class,$brand,$model,$description,$quantity,$adding_date,$sell_price,$buying_price];
        $dbc->prepare($query)->execute($data);
        echo "Thank you. The record has been sent successfully.<br><br>";}
    else{
        echo '<h1>Please use the contact form or don\'t leave an empty field!</h1>';
    }
    

    PDO will report it's errors already, without any extra code required.
    and you should be using prepared statements

    0 讨论(0)
  • 2021-01-26 09:04

    If we have a look at the PDO manual and look up for the PDO class there is no connect_error property anywhere. But if we check mysqli manual we see it right there. You have to choose a database library and stick to it, they cannot be mixed.

    I always recommend to configure PDO to throw exceptions as you already do (although connection errors in particular will always through an exception no matter your settings) and not care to catch them unless you want to do something specific with them.

    0 讨论(0)
  • 2021-01-26 09:12

    There is no connect_error. You should use exception:

    try {
        $dbh = new PDO($dsn, $user, $password);
    } catch (PDOException $e) {
        echo 'Connection failed: ' . $e->getMessage();
    }
    

    Or if you do not want exception you can try errorCode and errorInfo

    0 讨论(0)
提交回复
热议问题