How to connect MySQL using PHP?

You can connect your MySQL with PHP using the below methods.

Method 1 - PHP extension(mysqli)

 

Use the following code to connect the MySQL. Select the database you want to connect to and replace the username, password, and dbname with your details.

<?php
$mysqli = mysqli("localhost", "username", "password", "dbname");
?>

 

Once you execute the above code it will connect to MySQL, you need to select the database. You can run queries and perform various operations using PHP scripts.

Method - 2 Connect MySQL using the PHP data objects(PDO)

 

The MySQL PHP extension can be only used with MySQL databases but PDO gives you the ability to create code which can handle different types of database.

Use the below code to connect to MySQL using the PDO. Replace the username, password, and dbname in the code with your database credentials.

<?php
    $myPDO = PDO('mysql:host=localhost;dbname=dbname', 'username', 'password');
?>

 

Method - 3 Legacy MySQL functions(mysql_connect)

 

The PHP MySQL functions( with mysql_connect) are deprecated in PHP version 5.5 and will be removed from the PHP in the near future so use it only when it is necessary.

Use the following code to connect to MySQL using the MySQL function(mysql_connect), replace the username, password, and dbname in the code with your details.

<?php
    mysql_connect('localhost','username','password');
    mysql_select_db("dbname");
?>			

 

Method - 4 Connect to Remote MySQL using PHP

 

In the previous 3 methods, we have used PHP scripts to connect to the MySQL database in a local environment. But if you want to connect to MySQL database on a remote server you can use the below mysqli code.

You will need to replace the localhost with your MySQL server IP or the hostname of your server. Also replace the username, password, and dbname.

<?php
    $mysqli = mysqli("YOUR SERVER IP", "username", "password", "dbname");
?>			



  • 0 Users Found This Useful

Was this answer helpful?

Related Articles

How to generate MySQL (backup) dump from the command line in Windows VPS?

This article will assist you how to generate MySQL (backup) dump from the Command line in the...

How to Clone MySQL database using PhpMyAdmin?

Database clone is a process to create a separate copy of the database. You can also use it as...

How to Enable Relation View in phpMyAdmin?

The option Relation View is probably one of the best features available in phpMyadmin. Sometimes...

Fix - Collection Max error, Cannot Connect to Server

Problem Statement Recently one of our customers was unable to connect to Collection Max and...

How to change phpMyAdmin password?

Following tutorial will guide you to reset the phpMyAdmin password. We assume that you have...