How to Connect MySQL with PHP

In this tutorial you will learn how to connect mysql with php and access data from your database. We’ll use the sql connect function in order to connect to our database then we’ll learn how to forcefully close our connection using the mysql close function.

Step 1: Joining PHP script to database

If you want to access data such as validating login details of a user or registering a new user, you need to access your database. connecting to mysql with php, you have to use the function “mysql_connect”.

connecting a PHP script to database

Step 2: Various parameters of connect function

While connecting to mysql with php the function “mysql_connect” has three parameters; servername, username and password. The first parameter of the function “servername” specifies the server to which the connection is to be made. The default value of this parameter is localhost. This is an optional parameter. The second parameter “username” specifies the user name with which we login into our database. The default value of this parameter is the name of the user who is the owner of the particular server process. Again, this is also an optional parameter. The third parameter “password” specifies the password with which you can login into the database.

Different parameters of  connect function

Step 3: Saving connection is a variable

The connection that is created with the database can be stored in a variable. In this way, it can be checked, if the connection has been created or otherwise an error cannot be generated in case of a failure of a connection.

storing connection is a variable

Step 4: Closing a connection in php

Normally, a connection ,which have been successfully created, terminates when the scripts end. But, a connection can also be forcefully closed before the end of the script by calling the function “mysql_close” in anywhere in the script.

forcefully closing a connection in php

This is pretty much all we have to share in order to guide you to how to connect mysql with php.