Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Connecting MySQL database with MySQLi Object Oriented style

    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 387
    Comment on it

    My previous article "How to connect MySQL database using MySQLi procedural function" demonstrates the use of MySQLi procedural function mysqli_connect() is used to connect with a MySQL database and MySQLi extension also provides an Object Oriented interface for connecting to database.

     

    MySQLi Object Oriented Style     

    To open a connection to MySQL database using MySQLi Object Oriented style we use constructor of mysqli class (mysqli::__construct) which is an alias of mysqli_connect(). On successful connection, it returns an object which represents the connection.

     

    Note : It also returned an object on Failure also (With Object Oriented style). To check the failure of connection we can use either $con->connect_error or mysqli_connect_error().

     

    Syntax : mysqli::__construct(host_name, username, password, db_name, port, socket)

    class mysqli {
     __construct ($host_name, $username, $password, $db_name, $port, $socket)
    }
    $con = new mysqli($host_name, $username, $password, $db_name, $port, $socket);

     

    Parameters Description :

    host_name : Specifies a host name or an IP address of MySQL server.

    username : Specifies the MySQL username

    password : Specifies the MySQL password

    db_name : Specifies the default database to be used

    port : Specifies the port number to connect to the MySQL server

    socket : Specifies the socket name or named pipe

     

    Example :

    <?php
    $host_name = "localhost";
    $username = "username";
    $password = "password";
    $database = "test";//database name
    
    // Create connection
    $con = new mysqli($host_name, $username, $password, $database);
    
    // Check connection
    if (!$con) {
      echo "Error: " . $con->connect_error; die;
    }
    echo "Connection to database : ".$database." created successfully on server : ".$con->host_info;
    ?>

     

    Output : Connection to database : test created successfully on server : Localhost via UNIX socket

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: