Advanced Java and Web Technologies for JNTUK
Blog providing beginner tutorials on different web technologies like HTML, CSS, Javascript, PHP, MYSQL, XML, Java Beans, Servlets, JSP and AJAX

11/03/2015 Categories: MYSQL and PHP. No Comments on Database Access in PHP

This article explains how to connect to a database and display the data in a table. MYSQL is used as the DBMS and the PHP script connects through mysqli functions to display data.


Relational databases are the primary choice for data storage in the Web. A DBMS provides a database along with a set of tools to manage the data in the database. One example for DBMS is MYSQL. More than half of the websites in the Internet are created using PHP and the data store as MYSQL.


The steps required to access data from a table in a database provided by MYSQL can be summarized as follows:

  • Establish or open a connection to the MYSQL server.
  • Select a database.
  • Execute the query against the database.
  • Process the result returned by the server.
  • Close the connection


To work with MYSQL databases, PHP provides in-built support in the form of predefined functions. To establish a connection with the MYSQL server, use the function mysql_connect which accepts three optional parameters.


First parameter is the server name, second parameter is the MYSQL server’s user name and the third parameter is the password for MYSQL server. If the connection to MYSQL fails, the function returns false. This function is generally used in conjunction with die function which can be used to print errors using the function mysql_error and terminate the execution of the script.


After opening a connection to the database, a database must be selected to execute the SQL queries. A database can be selected by using the function mysql_select_db which accepts a single string parameter, the name of the database.


After selecting a database, the next step is to specify the query which is generally stored as a string in a variable. This variable will be passed as a parameter to the function mysql_query which executes the query against the database.


The result of execution of the query can be stored in a variable. The result can be parsed row by row as an array by using the function mysql_fetch_array.


Below is a list of functions provides by PHP to work with MYSQL databases:




Below example demonstrates user validation against the details stored in a database using PHP and MYSQL:



Related Links:

Note: Do you have a question on this article or have a suggestion to make this article better? You can ask or suggest us by filling in the below form. After commenting, your comment will be held for moderation and will be published in 24-48 hrs.

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll Up