
We have now gone over how to connect to a database using PHP, as well as some of the essential SQL queries. Finally we can put these two lessons together and query the database within PHP. Executing queries in PHP versus directly to MySQL is more or less the same.
Before we can begin executing MySQL queries via PHP, we need to connect to MySQL and select our database. Please see that article for details on how to do that, as we are just going to be going over the querying part today.
To execute MySQL queries, we’ll be using the PHP function mysql_query(). Just as the name implies, this functions allows you to send SQL queries to the connected MySQL database. Let’s take a look at a basic example:
[php]mysql_query("SELECT [field_names] FROM [table_name]");[/php]
We encase the SQL query in double quotes (as opposed to single quotes) because we will need to use single quotes to wrap around values. Otherwise we would have to escape the single quotes each time, which is far from ideal. There is a glaring problem with the above code. If you were to make an error in your query, the function will not output an error (the function will return false), and any code relying on this query will not work correctly (which could be hard to debug).
The solution to this is to ensure that if mysql_query() returns false we stop the execution of the rest of the file, and output the error MySQL returned. We can use an or exit() statement and use the mysql_error() function to get the last error MySQL reported. Let’s look at the above example with this error handling added:
[php]mysql_query("SELECT [field_names] FROM [table_name]") or exit(‘A MySQL error has occurred: ‘ . mysql_error());[/php]
A quick note on exit(): The functions exit() and die() are equivalent and there’s no standard on which to use. As such, you’ll may see a different one than you are used to in other’s programming. Just wanted you to be aware.
If you which to use values (such as in a where clause), they must be encased in single quotes, even when you’re using a variable as the value.
When the MySQL query is successful, the function will return a resource. You’ll need to use some other functions to be able to handle and process a resource. Which is what we’ll be covering next week.




