A database query from PHP is basically a MySQL command wrapped up in a tiny PHP function called mysql_query(). This is where you use the basic SQL workhorses of SELECT, INSERT, UPDATE, and DELETE that we discussed in Chapter 13. The MySQL commands to CREATE or DROP a table (but not, thankfully, those to create or drop an entire database) can also be used with this PHP function if you do not wish to make your databases using the MySQL client.
You could write a query in the simplest possible way, as follows:
mysql_query(“SELECT Surname FROM personal_info WHERE ID<10”);
PHP would dutifully try to execute it. However, there are very good reasons to split up this and similar commands into two lines with extra variables, like this:
$query = “SELECT Surname FROM personal_info WHERE ID<10”;
$result = mysql_query($query);
The main rationale is that the extra variable gives you a handle on an extremely valuable piece of information. Every MySQL query gives you a receipt whether you succeed or not— sort of like a cash machine when you try to withdraw money. If things go well, you hardly need or notice the receipt—you can throw it away without a qualm. But if a problem occurs, the receipt will give you a clue as to what might have gone wrong, similar to the “Is the machine not dispensing or is your account overdrawn?” type of message that might be printed on your
Another advantage of assigning the query string to a variable is that you can more easily view the query if you run into an error. Of course, you would accomplish this by writing the variable out to an error log—never by dumping it out to the browser in production!
The function mysql_query takes as arguments the query string (which should not have a semicolon within the double quotes) and optionally a link identifier. Unless you have multiple connections, you don’t need the link identifier. It returns a TRUE (nonzero) integer value if the query was executed successfully even if no rows were affected. It returns a FALSE integer if the query was illegal or not properly executed for some other reason.