Connect to MySQL server in PHP

We are entering a bit advanced section of PHP, where we will be working with MySQL alongside PHP. Definitely a pre-requisite here would be the basic knowledge of standard SQL queries, as we will be presenting some most common ones in our current and upcoming articles on PHP with MySQL.

The first and foremost step to integration of MySQL with PHP will be to setup up a connection to our MySQL server. Until we do that, we wont be able to execute any of our SQL query.

Also this connection script should be kept portable to be included in every subsequent PHP files created, so we don’t have to write the connection script again and again.

So let’s create a PHP file named db_connect.php as –

Before you start performing operations with MySQL in PHP, make sure the MySQL server is up and running. If using XAMPP in your local system, make sure the MySQL service is started. Below is the snapshot of the same.

XAMPP MySQL Server Start

Note that the username and password have been specified to be ‘root’ and ‘ ‘ respectively, which are the default ones. However, we can update the password to be something else by navigating to phpMyAdmin (localhost/phpmyadmin/), clicking the ‘SQL’ tab and fire the following query –

Receive our updates to your inbox

Get more stuff like this
in your inbox

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.