How to connect MySQL?

Irina Cheverda
Irina Cheverda
December 19, 2014
How to connect MySQL?

Watch the video

How to connect MySQL?

In this article we will look at how to connect the MySQL database to your project using the PHP language. For this you need to create a database. You can read about how to do this in the Miscellaneous questions about software section.

You will also need the following information:

  • database name;
  • DB username;
  • database password;
  • db host address

The database in PHP is connected using the function mysql_connect - to connect to the server and mysql_select_db - to select the desired database.

Syntax for connecting to the server

  • $ connect = mysql_connect (“database address”, “username”, “password”));
  • mysql_select_db (“DB Name”, $ connect);

For convenience, we enter the database data into variables. As a result, the script will look like this:

  • <? php $ host = "localhost"; // database address (localhost or IP address) $ username = "admin"; // Database username $ pass = "*******"; // Database password
  • $ dbName = "dataBase"; // DB name
  • $ connect = mysql_connect ($ host, $ username, $ pass);
  • mysql_select_db (“$ dbName”, $ connect); ?>

This script can be placed in a separate file and connected with the help of include.

However, in a real project, no one uses the script in this form. Add error handling.

Error handling syntax

  • if (! $ connect) {echo ("Database is not connected!"); }
  • if (mysql_select_db ($ dbName)) {echo "Database $ dbName is online!"; } else {die ("Database $ dbName not found!");}

This PHP syntax is widely used when there is a question about how to connect the MySQL database to the site.