PHP mysql_query() Function

After establishing a connection to the MySQL and its specific database, it is time to work with the database records. Mostly, we need to insert, update, retrieve and delete records from the database tables.

PHP provides a built-in function mysql_query() to achieve these tasks along with others. This chapter will explain how to use the mysql_query() function to do these operations.

How to use the mysql_query() function?

This is how the mysql_query() function is used:

mysql_query(‘sql statement’,connection)

Where:

  • SQL statement = There you will place either direct or a string variable containing an SQL statement.
  • Connection = You can also place connection object here if a connection is not already established with a database.

Examples of using mysql_query()

Before we go through the examples, we are assuming that:

  • You have the knowledge of SQL insert, delete, update statements.
  • You have installed MySQL database.
  • You have created a DB name = testdb.
  • You have created a user = testuser.
  • You have assigned this password to above user = testpassword.
  • You have created a table = tblstaff.

To learn about SQL insert, delete and update statements go to SQL tutorials.

PHP mysql_query to insert data

This example enters a record into the tblstaff in testdb database

This should be the output:

MySQL Connected successfully

Connected to Database

Entered data successfully

This is a basic example of how to use mysql_query to insert data into a table of MySQL database.

In real time applications, this will be selected by users/visitors of your website through a user interface in HTML or some other front end. In that case, you have to capture values from the front end like HTML form, store data into PHP variables (temporarily), make an SQL statement and use the above example approach.

PHP MySQL function to update data

This example updates/modify a record of tblstaff in testdb database.

Output:

MySQL Connected successfully

Connected to Database

Record updated successfully

mysql_query to select data and displaying by mysql_fetch_array

This example selects data from the tblstaff table in the testdb database. After fetching data from tblstaff, it also displays the records.

Output:

This example will output HTML table in the browser showing all records fetched from the tblstaff table in the testdb database.

 

Note: The mysql_query PHP function is deprecated from the PHP 5.5.0, source.