The SELECT query plays a very
important role when working
with PHP and MYSQL. SELECT
is used when you are trying to
retrieve data from the database.
In this blog I am providing four
examples of how to retrieve that
data in the most efficient and quick
way. If you are planning on using
MYSQL with PHP extension I would
recommend that you become familier
with those examples.
1) The following query retrieves data from one field of the specified row found
in the result set:
$query = “SELECT itemid, name FROM item ORDER BY name”;
$result_query = mysql_query($query);
$itemid = mysql_result($result_query, 0, “itemid”);
$name = mysql_result($result_query, 0 , “name”);
2) The following query retrieves an entire row of data from result set, placing
the values in an indexed array:
$query = “SELECT itemid, name FROM item ORDER BY name”;
$result_query = mysql_query($query);
while (list($itemid, $name) = mysql_fetch_row($result_query))
{
Echo “Item: $name ($itemid) <br />”;
}
3) The following query retrieves results solely by numerical indeces:
$query = “SELECT itemid, name FROM item ORDER BY name”;
$result_query = mysql_query($query);
while ($row = mysql_fetch_array($result_query, MYSQL_NUM))
{
$name = $row[1];
$itemid = $row[0];
Echo “Item: $name ($itemid) <br />”;
}
4) The following query is almost the same as the previews but uses objects
instead of array:
$query = “SELECT itemid, name FROM item ORDER BY name”;
$result_query = mysql_query($query);
while ($row = mysql_fetch_object($result_query))
{
$name = $row -> name;
$itemid = $row -> itemid;
Echo “Item: $name ($itemid) <br />”;
}