Querying and formatting

resource mysql_query ( string query [, resource link_identifier])

int mysql_num_rows ( [resource result])

The majority of your interaction with MySQL in PHP will be done using the mysql_query() function, which takes one parameter - the SQL query you want to perform. It will then perform that query and return a special resource known as a MySQL result index - this resource contains all the rows that matched your query.

This result index resource is the return value of mysql_query(), and you should save it in a variable for later use - whenever you want to extract rows from the results, count the number of rows, etc, you need to use this value.

One other key function is mysql_num_rows(), which takes a MySQL result index as its parameter, and returns the number of rows inside that result - this is the number of rows that matched the query you sent in mysql_query(). With the two together we can write our first database enabled script:

("localhost", "phpuser", "alm65z");
$result = mysql_query("SELECT * FROM usertable");
$numrows = mysql_num_rows($result);
"There are $numrows people in usertable\n";

As you can see, we capture the return value of mysql_query() inside $result, then use on the very next line - this MySQL result index is used quite heavily, so it is important to keep track of it. The exception to this is when you are executing a write query in MySQL - you might not want to know the result.

One helpful feature of mysql_query() is that it will return false if the query is syntactically invalid - that is, if you have used a bad query. This means that very often it is helpful to check the return value even if you are writing data - if the data was not written successfully, mysql_query() will tell you so with the return value.


Next chapter: Disconnecting from a MySQL database >>

Previous chapter: Connecting to a MySQL database

Jump to:


Home: Table of Contents

Follow us on Identi.ca or Twitter

Username:   Password:
Create Account | About TuxRadar