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");
?>			



Related Articles

How to turn on/off Mysql strict mode in the Windows server?

By default in the windows server, the strict mode will be enabled on MySQL. Please refer to the...

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 Enable Relation View in phpMyAdmin?

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

How do I connect to MySQL server from phpMyAdmin?

This article will guide you on how to connect to MySQL server from phpMyAdmin. You can obtain...

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...

  • 0 Users Found This Useful

Was this answer helpful?