9.4.2 Querying and formatting: mysql_query() and mysql_num_rows()This is NOT the latest copy of this book; click here for the latest version.
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:
<?php
mysql_connect("localhost", "phpuser", "alm65z");
mysql_select_db("phpdb");
$result = mysql_query("SELECT * FROM usertable");
$numrows = mysql_num_rows($result);
print "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.
|
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.
My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!
|