Creating Connection

PHP and MySQL
PHP and MySQL : Home
Introduction to MySQL
mysqli class
Creating Connection
Performing Query
Handling Results

Connection
You can create a connection by creating a new object of mysqli class. You need to pass atleast host for creating new connection. If you are using local MySQL server the host would be "localhost". The default username is "root" and password is "".

<?php
// Creating object of mysqli class
$mysqli_object = @new mysqli("localhost","user","password","db");

// Checking if there was some error occured
if($mysqli_object->connect_errno){
    // Printing error code and error
  echo "Connection unsuccesful ".$mysqli_object->connect_errno." ";
    echo $mysqli_object->connect_error;
}
else{
    echo "Congrats You did it, Connection Established";
}
?>


Output
Connection unsuccesful 1049 Unknown database 'db'

In this case there was no database named 'db', so an error was thrown with error code 1049.
->@ is used to avoid the error thrown by the new mysqli() statement.


Creating Connection (Procedural Method):

<?php
// Creating connection
$connection = @mysqli_connect("localhost","user","password","db");

// Checking if there was some error occured
if(mysqli_connect_errno()){
    // Printing error code and error
    echo "Connection unsuccesful ".mysqli_connect_errno()." ";
    echo mysqli_connect_error();
}
else{
    echo "Congrats You did it Connection Established";
}
?>


Output
Connection unsuccesful 1049 Unknown database 'db'

No object was created here, only functions are called.

We will suggest you to follow any one method as learning both can create confusion and that you should surely avoid.

Login to Track Your Progress