So far we have learnt how to open (and close) a connection to a database server and select the MySQL database to be used. The next step is to learn how to run a MySQL query on the database by using PHP.
PHP provides a handy function appropriately called mysql_query which runs queries on our database and returns the results to us.
The MySQL query tutorial below shows you how.
The simplest way of querying a MySQL database from PHP is:
$result = mysql_query($query);
Where query is a string or variable containing the SQL to be executed.
Take a look at the following PHP code:
<?php $connection = mysql_connect("localhost","apache","foobar"); mysql_select_db('tutorial_arena'); $sql = "SELECT * FROM tutorials"; $result = mysql_query($sql); // perform the query mysql_close($connection); ?>
The $result variable is used to store the output of the query that was executed. Many times, queries such as the SELECT query will return some data. We need to set up some sort of variable so that we can process the data returned from the MySQL query later.
The mysql_query function accepts a single SQL query only. That is, you can only send a single query each time when calling the function.
We hope this PHP tutorial has been helpful in getting you to understand how to query a MySQL database from PHP.