home support FAQ resources services partners contact us contact us
 MySQL Tutorial Previous  Next  
 

$query = "SELECT last_name, first_name FROM president";
$result_id = mysql_query ($query)
or die ("Query failed");
while ($row = mysql_fetch_object ($result_id))
printf ("%s %s\n", $row->first_name, $row->last_name);
mysql_free_result ($result_id);

What if your query contains calculated columns? For example, you might issue a query that returns values that are calculated as the result of an expression:

SELECT CONCAT(first_name, ' ', last_name) FROM president

A query that is written like that is unsuitable for use with mysql_fetch_object(). The name of the selected column is the expression itself, which isn't a legal property name. However, you can supply a legal name by giving the column an alias. The following query aliases the column as full_name:

SELECT CONCAT(first_name, ' ', last_name) AS full_name FROM president

If you fetch the results of this query with mysql_fetch_object(), the alias allows the column to be accessed as $row->full_name.

Testing for NULL Values in Query Results

PHP represents NULL values in result sets as unset values. One way to check for NULL in a column value returned from a SELECT query is to use the isset() function. The following example selects and prints names and email addresses from the member table, printing "No email address available" if the address is NULL:

$query = "SELECT last_name, first_name, email FROM member";
$result_id = mysql_query ($query)
or die ("Query failed");
while (list ($last_name, $first_name, $email) = mysql_fetch_row ($result_id))
{
printf ("Name: %s %s, Email: ", $first_name, $last_name);
if (!isset ($email))
print ("no email address available");
else
print ($email);
print ("\n");
}
mysql_free_result ($result_id);

A related function is empty(), but empty() returns the same result for NULL and empty strings, so it's not useful as a NULL value test.

In PHP 4, you can test for NULL values using the PHP NULL constant by using the === identically-equal-to operator:
Previous  Next  
Link Partners: Asia florist, Flowers to India, Hong kong flowers, Site submit, Cheap web hosting, China florist, Japan florist