How to use PHP mysql_query() to Insert, Select, Update and delete records from MySQL database

The mysql_query() function

After establishing a connection to MySQL and its specific database, it is time to work with database records. Mostly we need to Insert, Update, retrieve or select and Delete records from the database tables.

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

Syntax of mysql_query()

mysql_query(‘sql statement’,connection)


  • 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 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 or MySQL 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 to Update data

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


MySQL Connected successfully

Connected to Database

Record updated successfully

mysql_query to Select data and displaying by mysql_fetch_array

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


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


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

Was this article helpful?

Related Articles

Leave A Comment?