How to Connect/Link MySql Database with Php [Connectivity Code ]

<?php
/*--------------------------------CONNECTIVITY CODE SYNTAX--------------------------------*/

     error_reporting(E_ERROR | E_PARSE);   //optional code to remove warning messages, if any.

     $conn=mysqli_connect("localhost","MySqlUserName","MySqlPassword","MySqlDatabasename");
        if ($conn)
          {
           echo "database connected successfully","<br>";
          }
        else
          {
           die("Connection Aborted:" . mysqli_connect_error());
          }
    
      mysqli_close($conn);      //optional,to close the connection properly.
?>
/*-------------------------------------------OR---------------------------------------------*/
<?php
     
     $servername="localhost";       //or local server ip address="127.0.0.1";
     // $servername="127.0.0.1";
     $username="mysqlusername";
     $password="mysqlpassword";
     $databasename="mysqldatabasename";     

     error_reporting(E_ERROR | E_PARSE);   //optional code to remove warning messages, if any.

     $conn=mysqli_connect($servername,$username,$password,$databasename);
        if (!$conn)
          {
           die("Connection Aborted:" . mysqli_connect_error());
          }
        else
          {
           echo "database connected successfully","<br>";
          }
    
     mysqli_close($conn);      //optional,to close the connection properly.
?>

/*-------------------------------------------OR---------------------------------------------*/
<?php
    error_reporting(E_ERROR | E_PARSE);

    $conn = mysqli_connect('serveraddress','username','password');
        
    if (!$conn) 
	{
        die('Could not connect: ' . mysqli_error($conn));
    }
	
    mysqli_select_db($conn,"databasename");    
    
?>

/*----------------------------------------Examples----------------------------------------*/
<?php
     error_reporting(E_ERROR | E_PARSE);  //optional code to remove warning messages, if any.

     $conn=mysqli_connect("localhost","root","","codershelpline");
        if ($conn)
          {
           echo "database connected successfully","<br>";
          }
        else
          {
           die("Connection Aborted:" . mysqli_connect_error());
          }
    
      mysqli_close($conn);      //optional,to close the connection properly.
?>

/* NB: 
- To open MySql Database first time, by default MySql username is     
  root and password is empty/blank. 
- We can normally put the above connectivity code at top of the    
  page/just above the required place in the program/ in separate  
  folder outside the program. */

Loading

Categories: Php Proj

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.