Newbie Question:
I just started using MYSQL & PHP. I did a lot of reading on how to making a connection to MYSQL
through PHP. I liked the whole concept of PEAR and how easy it was to migrate from one Database
to another. What I have created is a include file call DBCommon.php that contains my DB settings.
<?PHP
function GetRS($sql)
{
global $result;
// Database Type
// Supported database types include "fbsql", "ifx", "mssql", "oci8", "pgsql", "ibase", "msql", "mysql", "odbc" and "sybase".
$db_type='mysql';
// Host name
$db_host='localhost';
// User name
$db_user='USERNAME';
// Password
$db_pass='PASSWORD';
// Database name
$db_name='DATBASE NAME';
// Include the DB abstraction layer
require_once("DB.php");
// Connect to Database
$db = DB::connect( "$db_type://$db_user:$db_pass@$db_host/$db_name" );
if (DB::isError($db)) {
die("Can't connect to $db_name on $db_host. " . DB::errorMessage($db));
}
// Set fetch mode
// DB_FETCHMODE_ORDERED (default), DB_FETCHMODE_ASSOC and DB_FETCHMODE_OBJECT.
$db->setFetchMode(DB_FETCHMODE_ASSOC);
// Execute query
$result = $db->query($sql);
if (DB::isError($result)) {
die("Error in query: $sql. " . DB::errorMessage($result));
}
// Close database connection
$db->disconnect();
}
?>
From any page that I need a database connection I would simply add the following code:
<?PHP
include ('include/dbcommon.php');
$sql='select * from TABLE';
GetRS($sql);
while($row = $result->fetchRow())
{
echo $row['FIELD'] ."<BR>\n";
}
echo "\n[" . $result->numRows() . " rows returned]\n";
?>
If you notice a the top of the code I made a global variable called $result. Does anybody see a problem
by making the variable global?