Querying and formatting

resource mysqli_query ( resource link_identifier, string query [, int mode = MYSQLI_STORE_RESULT])

int mysqli_num_rows ( [resource result])

The majority of your interaction with MySQL in PHP will be done using the mysqli_query() function, which takes at least two parameters: the database connection you want to query, and the SQL query you want to perform. It will then perform that query and return a special resource known as a MySQL result index, which contains all the rows that matched your query.

This result index resource is the return value of mysqli_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 mysqli_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 mysqli_query(). With the two together we can write our first database enabled script:

    $db = mysqli_connect("localhost", "phpuser", "alm65z", "phpdb");
    $result = mysqli_query($db, "SELECT * FROM usertable");
    $numrows = mysqli_num_rows($result);
    print "There are $numrows people in usertable\n";

As you can see, we capture the return value of mysqli_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 mysqli_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, mysqli_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

Copyright ©2015 Paul Hudson. Follow me: @twostraws.