How to connect to MySQL database using PHP

How to connect to MySQL database using PHP

To be able to connect to a MySQL database, you will need the following MySQL Database Connection Credentials:

  • Database Name
  • Host Name
  • User Name
  • Password

Before you can get content out of your MySQL database, you must know how to establish a connection to MySQL from inside a PHP script. To perform basic queries from within MySQL is very easy. This article will show you how to get up and running.

Let’s get started. The first thing to do is connect to the database.The function to connect to MySQL is called mysql_connect. This function returns a resource which is a pointer to the database connection. It’s also called a database handle, and we’ll use it in later functions. Don’t forget to replace your connection details.

<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$dbhandle = new mysqli($servername, $username, $password);
// Check connection
if ($dbhandle->connect_error) {
die("Connection failed: " . $dbhandle->connect_error);
} 
echo "Connected to MySQL successfully";
?>

All going well, you should see “Connected to MySQL successfully” when you run this script. If you can’t connect to the server, make sure your password, username and hostname are correct.

Walid BaniHani

 

College of Applied Sciences - Al Rustaq

Leave a Reply

Your email address will not be published. Required fields are marked *