Watch the video

How to connect MySQL?

In this article, we'll look at how to connectMySQL database to your project using the PHP language. To do this, you will need to create a database. How to do this, you can read in the section Miscellaneous questions about software.

You will also need the following information:

  • name of the database;
  • database user name;
  • password to the database;
  • address of the database host.

The database in PHP is connected using 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", "user name", "password"));
  • mysql_select_db ("Database name", $ connect);

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

  • <? php $ host = "localhost"; // address of the database (localhost or IP address) $ username = "admin"; // DB user name $ pass = "*******"; // Password to the database
  • $ dbName = "dataBase"; // The name of the database
  • $ connect = mysql_connect ($ host, $ username, $ pass);
  • mysql_select_db ("$ dbName", $ connect); ?>

This script can be put into a separate file and connected with the help of include.

However, in a real project, nobody uses the script in this form. Let's add error handling.

Error Handling Syntax

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

This PHP syntax is widely used when it comes to the question of how to connect the MySQL database to the site.

Comments 0