Fatal error Call to a member function prepare() on null

前端 未结 1 1706
故里飘歌
故里飘歌 2020-12-03 20:12

I am trying to check if email was already used in Registration. It worked well when I was working on it in the school but now it suddenly shows an error:

相关标签:
1条回答
  • 2020-12-03 21:00

    Edit: (I figured it out).

    I finally figured out why your code is not working and my original answer no longer applies, which I have stricken out.

    The reason why your connection does not work, is because you left out the dbpass constant from the connection parameter.

    $db = new PDO(
    "mysql:host=" .dbserver. ";dbname=" .dbname,dbuser,dbpass,
    array(
    PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8",
    PDO::MYSQL_ATTR_INIT_COMMAND => "SET CHARACTER SET utf8"
    ) );
    
    • Even though you may not have a password set for it, it is still required to be part of the parameters.

    • http://php.net/manual/en/ref.pdo-mysql.connection.php


    Original answer, which no longer applies. (see edit above).

    TBH, I wasn't able to reproduce the error, amidst a great effort.

    However; after tinkering with this, have discovered that PDO (least, the one on my server), won't allow for constants be used as the first 2 parameters in the DSN.

    Sidenote: If what you say worked at your school, then there may be a setting used that I don't know about.

    You can however, assign variables to the constants, then use those variables in the DSN.

    $servername = "localhost";
    $dbname = "user";
    
    define("dbuser", "user");
    define("dbpass", "");
    
    $dsn = "mysql:host=$servername;dbname=$dbname";
    
    $username = dbuser; // variable equals constant
    $password = dbpass; // variable equals constant
    
    $options = array(
    PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8",
    PDO::MYSQL_ATTR_INIT_COMMAND => "SET CHARACTER SET utf8"
    ); 
    
    $db = new PDO($dsn, $username, $password, $options);
    

    For more information on PDO connection, visit:

    • http://php.net/manual/en/ref.pdo-mysql.connection.php


    Add error reporting to the top of your file(s) which will help find errors.

    <?php 
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    
    // rest of your code
    

    Sidenote: Error reporting should only be done in staging, and never production.

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