Difference between revisions of "PHP199"

From mi-linux
Jump to navigationJump to search
Line 31: Line 31:
 
A good tip for checking the information returned from the database is to use <pre> and print_r() which outputs arrays in a more readable form...
 
A good tip for checking the information returned from the database is to use <pre> and print_r() which outputs arrays in a more readable form...
  
e.g.
+
''Example''
  
 
Presuming the following SQL was used on the comics database...<br />
 
Presuming the following SQL was used on the comics database...<br />

Revision as of 12:25, 3 February 2007

Finding the number of rows returned

This is a small tip I haven't seen on the Wiki which shows you how to find the number of rows return from your MySQL queryies. The function mysql_num_rows() is the one to look for.

Example

<?
// Database connection here...

$sql = "SELECT title,author FROM comics';

$res = mysql_query($sql);

$total = mysql_num_rows($res);

if ($total == 0) {
  echo 'No rows were returned';
} elseif ($total == 1) {
  echo '1 row was returned';
} else {
  echo $total . ' rows were returned';
}
?>

/MJ

Viewing contents of array

A good tip for checking the information returned from the database is to use <pre> and print_r() which outputs arrays in a more readable form...

Example

Presuming the following SQL was used on the comics database...

SELECT title,author FROM comics LIMIT 1

This would return the title and author details for the first record in the table.

If you then used mysql_fetch_array() to return the details as an array and output it's contents wrapped in <pre> you get a nicely formatted view of the array and it's contents.

<?
// Database connection here...

$sql = "SELECT title,author FROM comics LIMIT 1';

$res = mysql_query($sql);

$row = mysql_fetch_assoc($res);

echo '<pre>'; print_r($row); echo '<pre>';

?>

Would print the following...

Array
(
    [title] => Elfquest
    [author] => Richard/Pini (Wendi)
)

Can be especially useful when using multidimensional arrays, or when you have a lot of fields returned from the database.

/MJ