Posts Tagged ‘query’

How to order the results of MySQL query?

Usually most of the work done with MySQL involves pulling down data from a MySQL database. In MySQL, data is retrieved with the “SELECT” keyword. Think of SELECT as working the same way as it does on your computer. If you wanted to copy some information in a document, you would first select the desired information, then copy and paste.

How to include a conditional in my MySQL query?

You will usually need to apply some logic to the query that you apply to a table, and this is easily done with the WHERE keyword.
This will be followed by a fieldname, or list of them, and then the condition you want to be met.
Thus if you want to select only rows from a table WHERE the user is called Quentin you would do the follow:

$peeps = mysql_query("SELECT * FROM users WHERE firstname = 'Quentin'");
?>

How to group the results of a MySQL query?

If you want to group the results by a particular field value rather than listing all results individually, then you use the GROUP BY keyword.
Here is how the query might look:
SELECT columns FROM Table WHERE clause GROUP BY column ORDER BY column
Common mistakes are to apply the GROUP BY either before the WHERE clause or after the ORDER BY – make sure you get it right.
Also remember that you are returning aggregate data rather than every result as an individual row, therefore it can take a little bit of careful thinking as to when you should use GROUP BY and a realisation of what will be returned when you do.

How to find the number of rows affected by a query?

With mysql it is usually just a case of learning which function to use, and this is no exception.

The function you will want is mysql_affected_rows which you call after the query has run, and it will tell you how many rows were affected.