Queries and Results

Now that you have a physical connection to the database, you can interact with MySQL. The above example used the mysql_query( ) function to get all of the rows from the test table in our sample database:

state = mysql_query(connection, "SELECT test_id, test_val FROM test");

This function returns nonzero on error. Once you send a query, you should therefore check the return code to make sure the query executed properly.

if(state != 0 ) {
    /* Error! */
}

If the return code is 0, you can access any results through the mysql_store_result( ) function:

result = mysql_store_result(connection);

This function returns a pointer to the result set generated by the previous query executed against the specified connection. If that query did not generate results, or if you encounter an error getting to the results, this function returns null. The earlier example does not look for these states—we will go into them in more detail when we cover error handling later in the chapter.

The results given to you by the mysql_store_result( ) function are now under your control. They will exist in memory until you explicitly free them through the mysql_free_result( ) function. In this case, you should step through each row of the results and print the row’s values:

while( (row = mysql_fetch_row(result)) != NULL ) {
    printf("id: %s, val: %s\n", (row[0] ? row[0] : "NULL"),
           (row[1] ? row[1] : "NULL"));
}

Even though the test_id column in our database is a numeric column, we still treat it as ...

Get Managing & Using MySQL, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.