Common Steps to execute any SQL statements in PHP
All the SQL queries which do not return any data are the easiest ones to process in PHP. Almost all such queries follow a simple pattern as explained below.
- You create a MySQL connection as discussed in mysql_connect section.
- You select the database using the mysql_select_db() function.
- You define a string variable which stores the final SQL query. If the query is dynamic one, you ensure that valid SQL statement is prepared by using several dot operators wherever necessary.
Here I would like to add that the SQL statement can directly be passed to function. But in practical almost everywhere a string variable is used.
- You execute the SQL query by passing the string variable prepared in the previous step to the function mysql_query (); A typical query statement in PHP would look like
mysql_query($sql_statement);
That’s it. In PHP handling with mysql database is just a piece of butter.
For the select statements, the mysql_query() function returns the resultset. The returned resultset is further processed to fetch the actual data. This will be explained in the section to select records in PHP.
One last thing, the order of the statements given above might be different a little. But the order of statements should always like Connect to database - Select Database - Execute Query. In how many steps yuu reach the last step, it is up to you!