Saturday 31 May 2014

[Solved] Connect PHP with MYSQL & Select Database


INTRODUCTION 


Hi Everybody,

Most of the times we need to connect our PHP code to MY SQL database Server as backend. So today I am going to show you that how can we connect My SQL database as backend to PHP and select database after connection to server.

There is a built in function mysqli_connect( ) or mysql_connect( ) by using which we can connect to our My SQL database server and mysql_select_db( ) to select database after connecting to server successfully. To create databases and table in My SQL Server using phpmyadmin panel is completely explained here.

So below is the code to connect PHP to MYSQL Server and select  database after successfull connection.

<?php

// Change values according to your credentials

$host = "localhost";
$user = "user";
$pass = "password";
$db = "mydbname";

$conn = mysql_connect($host,$user,$pass);

if($conn)
{
     echo "Successfully connected to server";
     
     $select = mysql_select_db($db, $conn);

        if($select)
        {
             echo "Database selected successfully";
        }
        else 
        {
              echo "Error: ". mysql_error( );
        }
         

}
else
{
    echo "Error: ". mysql_error( );
}

?>

If you have latest version of My SQL Server then you can also use mysqli_connect( )

<?php

// Change values according to your credentials

$host = "localhost";
$user = "user";
$pass = "password";
$db "mydbname";

$conn = mysqli_connect($host,$user,$pass,$db);

if($conn)
{
     echo "Successfully connected to server and selected database";
     
}
else
{
    echo "Error: ". mysql_error( );
}

?>


No comments:

Post a Comment