about


Scribe:

chrono

blog

Time

science!

book musings

gov

'punk

missle defense

jams

antiques

cultcha blog


Construct:

scripts & programs

on the town

snaps


Self:

creds (PDF)

key

missive


PHP: Post the results of a simple MySql Query on a Web Page

Say you want to post the results of a simple query from a MySQL database on a Web page, using PHP. You would think that all you'd need to do is assign a variable name to the results of the SQL query, and then ask PHP to print the variable.

It doesn't work that way. Instead of PHP printing the result, what gets printed is a mysterious message, like "Resource ID #3"

As explained here, the variable itself points to a place holder of sorts. To get the actual value, you have to use another MySQL function.

In this case that function would be mysql-fetch-row.

For example, within the PHP body of code, you do something like this:

   $QueryResult = mysql_query("select avg(Height) from Boys);

   $ResultInBetweenStep = mysql_fetch_row($QueryResult);

   $ResultPresent = $ResultInBetweenStep[0];

   echo($ResultPresent);  
In the above quote, we're getting the result of a query from a table called Boys that is the average of all the entries in the Height column. It is assigned to the variable $QueryResult.

In order to get the actual data from the query, the function mysql_fetch_row is applied to $QueryResult, and the results are stored in another variable, $ResultInBetweenStep.

The final step is to assign a variable to the first row of $ResultInBetweenStep only (which would be the *only* row in the query, as the average function will return a single number), which, here, is called $ResultPresent.

$ResultPresent can then be printed.

There are other MySql functions that allow you to extract more complex bits of information from a MySQL query. Check the mysql_fetch_* entries here for more info.--Joab Jackson