PHP MySQL connection

How to Connect PHP to a MySQL Database?

Before making database related actions you must create connection with MySQL server. Without making connection with MySQL server, you can not retrieve or store the data in database. In PHP, there is build in function mysql_connect present for making connection with database. mysql_connect function required 3 arguments. The syntax is mentioned below: Syntax


<?php
  mysqli_connect(servername, username, password);s
?>
Parameters Description
servername The first parameter is required and specifies the server name you want to connect to. It is an optional parameter, if you do not specify server name then its default value is “localhost:3306”.
username Second parameter required username for log in with MySQL server. It is an optional parameter, if you do not specify it then its default value is the user name who is owner of the server.
Password Third parameter required password of the server. It is an optional parameter, if you do not specify it then its default value is ""(blank).
mysqli_connect function returns a boolean value it returns true if connection made successfully else it returns false. The example is mentioned below:

Code

<?php
$connection = mysqli_connect("localhost", "marcus", "xyz123");

if (!$connection) {
    die("Could not connect: " . mysqli_connect_error());
}

echo "Connected successfully!";
?>

FAQ 1. What is mysqli_connect_error() in PHP? The mysqli_connect_error() function returns a description of the last connection error. It helps developers identify problems when PHP cannot connect to a MySQL database. 2. Is MySQLi better than MySQL in PHP? Yes. MySQLi is the improved MySQL extension for PHP. It supports prepared statements, transactions and both procedural and object-oriented programming styles. The old MySQL extension is no longer supported. 3. What is the difference between MySQLi and PDO in PHP? MySQLi is specifically designed for MySQL databases, whereas PDO supports multiple database systems through a common interface. Both support prepared statements and are suitable for modern PHP applications.