Archive:PHP and MySQL Programming/Database Connectivity: Difference between revisions

wikademia>Ralfe
No edit summary
wikademia>Ralfe
Line 31: Line 31:
== Retrieving data from a SELECT Query ==
== Retrieving data from a SELECT Query ==


There are many methods for retrieving data from a SELECT Query.


If we take, for example, the following code :
<?
# --- Connect To Database ---
$db = "db1";
$link = mysql_connect("localhost", "user", "pass");
mysql_select_db($db, $link);
# --- Select Info from Database ---
$result = mysql_query ("SELECT val1, val2 FROM tbl1");
?>
To now retrieve the data from the $result variable, we can use one of many methods. The recommended method, however, is to sequentially go through each row of the table, storing it into a one-dimensional array. We do this by using the mysql_fetch_row() function, passing it the variable intowhich the result is stored. Here is a simple example :
<?
while ($row = mysql_fetch_row($result)){
    foreach ($row as $field) {
      print "$filed . ";
    }
    print "<BR>";
}
?>
This will simply output the result in table-like format.
Here is another example of using this method :
<?
$counter = 0;
while ($row = mysql_fetch_row($result)){
    $val1[$counter] = $row[0];
    $val2[$counter] = $row[1];
    $counter++;
}
$numRows = $counter;
?>
The above example, simply splits the results up into multiple one-dimensional arrays, for easy manipulation.


== Closing a Database Connection ==
== Closing a Database Connection ==