Building the Sql Select Query

Building a SQL query is as easy as setting a variable to the string that is your SQL query. Of course, you'll need to use a valid SQL query, or MySQL returns with an error when you execute the query. The variable name $query is used since the name reflects its purpose, but you can choose anything you'd like for a variable name. The SQL query in this example is SELECT * FROM books.

Unlike when you used the mysql command-line client, the query does not have a semicolon at the end.

You can build up your query in parts using the string concatenate (.) operator: // Assign the query

' NATURAL JOIN authors'; $select.$column.$from.$tables.$where;

This code is a more flexible version of the following: // Assign the query

$query = "SELECT * FROM books NATURAL JOIN authors";

The query string could also use a variable in the WHERE clause to limit which rows are returned based on user information or another query.

Now that you have your query assigned to a variable, you can execute it.

Was this article helpful?

0 0

Post a comment