MYSQL Connect & Close

The #1 most important step of integrating MYSQL into your PHP script is connecting to the database. And while it is not strictly necessary to close the connection, it is always good practice to tie up any loose ends. Here we will learn how to do both.

The mysqli_connect() function is used to connect. It requires four parameters, in the following order: mysqli_connect(servername, username, password, databasename)

The value of "servername" will specify what server you need to connect to. Since the database is usually on the same server as the script/connection, the default value is "localhost".

The username and password should be self-explanatory. Your web host probably provided them already. The database name is whatever you named your database.

  $con = mysqli_connect("localhost","my_username","my_secret_password", "database_name");
  if (!$con) { die('Could Not Connect: ' . mysqli_error($con) . mysqli_errno($con)); }
    // Do Database Stuff Here

See what we did there? We have connected to our database and stored the connection details/handle in the $con variable for later reference. Then we tested our connection using the handle and told the script to stop working if the connection was faulty. And last but not least, we used mysqli_close() to close the open connection.

Notice the use of mysqli_error() and mysqli_errno(), two functions that help to debug MYSQL-related problems. These functions can be used separately, but used together they will tell you what problem occurred and give you the error number for that problem, enabling you to research the problem in more detail.

What could be more simple? (Don't answer that.)


Function Description
mysqli_connect() Opens a new connection to the MySQL server
mysqli_close() Closes a previously opened database connection
mysqli_errno() Returns the last error code for the most recent function call
mysqli_error() Returns the last error description for the most recent function call