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.

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

Change MySQL root password in WampServer

Change MySQL root password in WampServer

In this tutorial we are now going to see how to open the phpMyAdmin from the WampServer icon from the system tray and changing the root password.

Steps to change root password:

WampServer MySQL

  1. Open the MySQL console by selecting the menu shown above.

  3. After clicking on the “MySQL console” following console window will be opened where default password is empty so we hit one enter key to continue without typing –  

  5. Now in order to change the default password we need to type following query in the MySQL console (we are setting password as – “
    SET PASSWORD FOR root@localhost=PASSWORD('jordan');

  7. In the older versions of the phpmyadmin we need to manually change the password in the phpmyadmin config file but in the current version we can skip this step.

Updating the password of root or any user :

We can use following query in the mysql console for updating the query –

mysql> UPDATE mysql.user
WHERE User = "root";

In the above example we are setting password “AMMAN” to the user “root”.