MySQL is a popular open-source database management system that is widely used for storing and retrieving data. PHP is a popular programming language that is often used to create dynamic websites and web applications. In this blog, we will discuss how to connect MySQL using PHP.
Requirements:
Text Editor
Connecting MySQL using PHP
Before we start, make sure that you have installed the latest version of PHP and MySQL on your system. Here are the steps to connect MySQL using PHP:
First, open your PHP file and create a new variable to store the MySQL server name, username, password, and database name. For example:
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydatabase";
Next, create a new connection using the mysqli_connect() function in PHP. The mysqli_connect() function takes four parameters: servername, username, password, and database name.
$conn = mysqli_connect($servername, $username, $password, $dbname);
Check the connection to the database using the mysqli_connect_error() function in PHP. If the connection is successful, this function will return an empty string. If there is an error, it will return an error message.
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
Now you are connected to the MySQL database using PHP. You can execute SQL queries using the mysqli_query() function. For example:
$sql = "SELECT * FROM mytable";
$result = mysqli_query($conn, $sql);
Finally, close the connection to the database using the mysqli_close() function.
mysqli_close($conn);
Conclusion
Connecting MySQL using PHP is a simple process. You just need to create a new connection using the mysqli_connect() function, check the connection using the mysqli_connect_error() function, execute SQL queries using the mysqli_query() function, and close the connection using the mysqli_close() function. With this knowledge, you can start building dynamic web applications that interact with a MySQL database.
Full Script
Let's name this file database.php.
$sname = "servername"; //mostly localhost
$uname = "dbusername"; //mostly root on local machine
$password= "dbpassword"; //mostly blank on local machine
$dbname= "dbname";
$conn= mysqli_connect($sname, $uname, $password,$dbname);
if (!$conn) {
echo "Connection Unsuccessful";
exit();
}