How to connect to MySQL in Php

How to connect to MySQL in Php


In this article you are going to study that "how to connect to MySQL Database through Php".

Introduction:

PHP 5 and onward can work with a MySQL database using:
  • MySQLi extension (the "i" stands for improved)
Earlier versions of PHP used the MySQL extension. However, this extension was disfavored in 2012.




MySQLi extension is used to create a connection with a single database. 

MySQLi is both
  1. Object-oriented
  2. Procedural API

Alternative:

There is another extension named as PDO which is used to connect multiple databases to the system. All you want to do is change the connection string. 
PDO is only
  • Object-oriented

How to use MySQLi:

In this article our main focus should be on MySQLi extension. Because in starting things should be simple and easy to learn.

In MySQLi, there are further two types of  using this extension.

  1. Passing values directly.
  2. Passing by variables. (preferred)

So here is some explanation of using these methods.
  1. Passing values Directly:      

 In this code,the variable declared $con has the connection saved in it. Mysqli_connect is the function by which your code is connected to MySQL  Database. 
       This function has four parameters:
  • In very first slot you have to write the server, which is "localhost" (in both WAMP and XAMP).
  • Than you have to write the username of your PhpmyAdmin. This is by default "root" (WAMP and XAMP).
  • "Password" you have set for phpmyadmin. By default its BLANK ("").
  • At last the name of Database.

#Source_Code

<?php
          $con = mysqli_connect("localhost", "username" ,  "password" ,"Database_name");  
?>

      2. By passing variables:           

      The unique way is to declare the variables and put the information (same steps in first type) and then call these variables in the function parameters. 

#Source_Code

<?php
      
      $server="localhost";    
      $username="username";
      $pass="";
      $database="database_name"; 
      $con=mysqli_connect($server,$username,$pass,$database);
       if (!$con)
          {   
              die( "Connection Failed : " .mysqli_error($con) );    
           }
   
?>

The other function mysqli_error in the IF condition can be used in both types. this one is to check whether the connection we created is correct or not and if not this function will return the error of connection.

Note:

To know how to insert these values in the Database Click the Link.

To know how to Select data from Database. Click the Link.

Related Post: