Building and executing a query
Sending a query to MySQL from PHP is as simple as issuing it using the mysql_query function. Consider the following Examples :
<?php $query = "SELECT * FROM classics"; $result = mysql_query($query); if (!$result) die ("Database access failed: " . mysql_error()); ?>
First, the variable $query is set to the query to be made. In this case it is asking to see all rows in the table classics. Note that, unlike using MySQL’s command line, no semicolon is required at the tail of the query, because the mysql_query function is used to issue a complete query, and cannot be used to query by sending multiple parts, one at a time. Therefore, MySQL knows the query is complete and doesn’t look for a semicolon.
This function returns a result that we place in the variable $result. Having used MySQL at the command line, you might think that the contents of $result will be the same as the result returned from a command-line query, with horizontal and vertical lines, and so on. However, this is not the case with the result returned to PHP. Instead, upon success, $result will contain a resource that can be used to extract the results of the query. You’ll see how to extract the data in the next section. Upon failure, $result contains FALSE. So the example finishes by checking $result. If it’s FALSE, it means that there was an error and the die command is executed.