| Databases > MySQL/PHP | ||
|
The following information is about accessing your MySQL database using PHP + the PEAR database unit which is already installed on your webserver. ** Standard PHP/MySQL retrieval will be dealt with later Now we are going to construct a couple of simple MySQL/PHP files that demonstrate data retrieval from a MySQL database. We are calling this file dbconnect.php <?php
// This is the database connection file
$db_user = ' yourdatabaseusername' ; // Your database Username $db_pass = ' mysqlpassword' ; // Your database password $db_host = 'localhost' ; // Leave as is $db_name = ' yourdatabasename' ; // Your database name $db_engine = 'mysql' ; // Leave as is $datasource = $db_engine.'://' .$db_user.':' .$db_pass.'@' .$db_host.'/' .$db_name; $db = DB::connect($datasource); // attempt connection // if connection failed show error if(DB::isError($db)) { // database error reporting die($db->getMessage()); } ?>
This is the main PHP file that fetches and prints the data to the page. <?php // This is the PHP file that collect data from the database require_once 'dbconnect.php' ; // Import the dbconnect.php file which contains the database information $sql = 'SELECT * FROM tablename' ; // We are fetching ALL(*) data from the table 'tablename' $q = $db->query($sql); // Put the sql query into the variable q ($q) if(DB::IsError($q)) { die($q->getMessage()); } // Error trapping $x = 0; // Set a counter variable
while($result = $q->fetchRow(DB_FETCHMODE_OBJECT))
// While Loop Start $price = $result-> price; // This assumes there is a field in the table ' tablename ' called ' price ' $itemname = $result-> itemname; // This assumes there is a field in the table ' tablename ' called ' itemname ' If ($itemname) // Yes... There is an item, or items in the table ' tablename ' so do this..... { // Start If $x++; //Increase the value of x by 1 $price = sprintf("%01.2f", $price); // Format the price for the item in decimal } // End If echo "(".$x." ) ".$itemname. " - £".$price."<p>"; // Echo (print) the item list & prices to this web page until the While loop ends } // End While Loop ?> A quick word about the above echo statement..... MySQL & PHP Downloads MySQL Manual
# MySQL manual in Windows help format (.chm)
More Soon!..... :-/ |