|
Added on 15.11.09 |
| Clicks 2025 |
| Rating: 5.00 out of 5 from 2 raters |

Now we've got a table called 'books' with some data, very good, but not much useful if the data just reside in the database, let's have a look how to get it and how to show it in a web page dynamically with PHP.
$sql="SELECT
* FROM books";
$result = mysql_query($sql);
if (!$result)
{
die('Invalid query: ' . mysql_error());
} the above code is quite simple , as you can see ,starts with the
usual variables holding the credential and the connection to the
database,then,it has a
variable $sql that holds the sql statement,the the variable $result holds
the resultset of the PHP function
mysql_query.For SELECT,
SHOW, DESCRIBE, EXPLAIN and other statements returning resultset,
mysql_query() returns a
resource on success, or FALSE on error.
That explains the row
if (!$result) {
die('Invalid query: ' .
mysql_error());
if an error occurs,the code stops
and an error message will be printed on the page
For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error.
The code above returns only a resultset if succeeds,but not data, to have the data available for manipulate it,we need another step,see the following table
$sql="SELECT * FROM books";
$result = mysql_query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
while($row=mysql_fetch_assoc($result)){
echo $row['title'].", ";
echo $row['author'].", ";
echo $row['category'].", ";
echo $row['price']."<br>";
}
mysql_free_result($result);
}
The code above ouputs the following data:
Advanced Database Technology and
Design, Mario Piattini and Oscar Diaz, Database,$ 89.00
Conceptual Database
Design, Carol Batini Shamkant Navathe, Database, $ 96.8
A Guide to MySQL,
Philip J.Pratt, MySql, $ 55.35
Beginning Databases with MySQL, Richard
Stones, MySql, $ 48.9
basically all the data that was in the database,to obtain all
that is very simple,as you can see from this piece of codeWhile($row=mysql_fetch_assoc($result)){
echo $row['title'].", ";
echo $row['author'].", ";
echo $row['category'].", ";
echo $row['price']."<br>";
we used mysql_fetch_assoc
to fetch the data from the table and While
the condition was true we printed the result using
echo,All very simple