How to work with mysqli

How to connect to a MySQL database (object-oriented)

      $host = 'localhost'; 
      $username = 'mgs_user'; 
      $password = 'pa55word'; 
      $db_name = 'my_guitar_shop1'; 
      @b$db = new mysqli($host, $username, $password, $db_name);
      

How to connect to a MySQL database (procedural)

       $host = 'localhost'; 
       $username = 'mgs_user'; 
       $password = 'pa55word'; 
       $db_name = 'my_guitar_shop1'; 
       @ $db = mysqli_connect($host, $username, $password, $db_name);
      

Two properties of the mysqli object for checking connection errors

Property Description
connect_errno Returns the error number if an error occurred. Returns a NULL value if no error occurred.
connect_error Returns the error message if an error occurred. Returns a NULL value if no error occurred.

How to check for a connection error (object-oriented)

      $connection_error = $db->connect_error; 
      if ($connection_error != null) { 
        echo("Error connecting to database: $connection_error");
        exit(); 
      } 
      

How to check for a connection error (procedural)

      $connection_error = mysqli_connect_error(); 
      if ($connection_error != null) { 
        echo("Error connecting to database: $connection_error");
        exit(); 
      }
      

Description

Back