List:General Discussion« Previous MessageNext Message »
From:Paul DuBois Date:June 10 1999 4:51pm
Subject:Re: COUNT() - Explain please
View as plain text  
At 9:32 AM -0500 6/10/99, Barry wrote:
>Hi All,
>I am confused about something, although I have used it in the past, I don't
>understand why it worked !!!  :)
>The following snippet from another's question provides a good example:
>> mysql_query(&sock, "select count(*) from products")
>> result = mysql_store_result(&sock))
>> oneRow = mysql_fetch_row(result);
>> printf("%d", oneRow[0]);
>colum[0] of oneRow holds the result from "Count(*)". Why is this? Is there
>a general explaination of this in the docs somewhere? Is it just an SQL
>rule to follow when using different functions in a query?

The return value from mysql_fetch_row() is an array of strings.  You declare
variables of this type as:

MYSQL_ROW	row;			/* note: "row", NOT "*row"!!! */

Then you access column values as row[0], row[1], row[2], ...

Since the query in question returns only a single column of data, the value
is accesses as row[0] (oneRow[0] in the example above.)

>I've seen others use "Select Count(*) as thecnt" then reference the return
>as the variable "thecnt". How is this done?

You can refer to the count as "thecnt" only later in the SQL statement itself,
for example "SELECT name,COUNT(*) as thecount FROM ... GROUP BY thecount"

But you can't refer directly to thecnt from your C program.

>Suppose I had two or three functions returning results, how would I
>reference the return values from each?

Figure out which column the function value is, then reference the value as
row[i], where is is the appropriate column number.  Remember that the
value in row[i] is a string, so you'll need to perform a conversion if
you want to treat it as a number.  (That's why "printf("%d", oneRow[0]);"
have been "printf("%s", oneRow[0]);")

This stuff is explained in the C API chapter of the MySQL Reference Manual.

Paul DuBois, paul@stripped
Northern League Chronicles:
COUNT()Net-Lynx10 Jun
Re: COUNT()Jorge Santos10 Jun
  • Re: COUNT() - Explain pleaseBarry10 Jun
    • Re: COUNT() - Explain pleasePaul DuBois10 Jun
      • Re: COUNT() - Thanks everyoneBarry11 Jun
Re: COUNT() - Explain pleaseJim Faucette10 Jun