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