Check for database connection, otherwise display message

后端 未结 3 1249
暖寄归人
暖寄归人 2021-02-05 09:33

I would like to check if the website can connect to mySQL. If not, I would like to display an error saying that the user should try to access the page again in a few minutes...<

相关标签:
3条回答
  • 2021-02-05 09:56

    Try this:

    <?php
    $servername   = "localhost";
    $database = "database";
    $username = "user";
    $password = "password";
    
    // Create connection
    $conn = new mysqli($servername, $username, $password, $database);
    // Check connection
    if ($conn->connect_error) {
       die("Connection failed: " . $conn->connect_error);
    }
      echo "Connected successfully";
    ?>
    
    0 讨论(0)
  • 2021-02-05 10:03

    very basic:

    <?php 
    $username = 'user';
    $password = 'password';
    $server = 'localhost'; 
    // Opens a connection to a MySQL server
    $connection = mysql_connect ($server, $username, $password) or die('try again in some minutes, please');
    //if you want to suppress the error message, substitute the connection line for:
    //$connection = @mysql_connect($server, $username, $password) or die('try again in some minutes, please');
    ?>
    

    result:

    Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'user'@'localhost' (using password: YES) in /home/user/public_html/zdel1.php on line 6 try again in some minutes, please

    as per Wrikken's recommendation below, check out a complete error handler for more complex, efficient and elegant solutions: http://www.php.net/manual/en/function.set-error-handler.php

    0 讨论(0)
  • 2021-02-05 10:17

    Please check this:

    $servername='localhost';
    $username='root';
    $password='';
    $databasename='MyDb';
    
    $connection = mysqli_connect($servername,$username,$password);
    
    if (!$connection) {
    die("Connection failed: " . $conn->connect_error);
    }
    
    /*mysqli_query($connection, "DROP DATABASE if exists MyDb;");
    
    if(!mysqli_query($connection, "CREATE DATABASE MyDb;")){
    echo "Error creating database: " . $connection->error;
    }
    
    mysqli_query($connection, "use MyDb;");
    mysqli_query($connection, "DROP TABLE if exists employee;");
    
    $table="CREATE TABLE employee (
    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    firstname VARCHAR(30) NOT NULL,
    lastname VARCHAR(30) NOT NULL,
    email VARCHAR(50),
    reg_date TIMESTAMP
    )"; 
    $value="INSERT INTO employee (firstname,lastname,email) VALUES ('john', 'steve', 'johnsteve@yahoo.com')";
    if(!mysqli_query($connection, $table)){echo "Error creating table: " . $connection->error;}
    if(!mysqli_query($connection, $value)){echo "Error inserting values: " . $connection->error;}*/
    
    0 讨论(0)
提交回复
热议问题