FunktionerTips: En Wrapper klass för databaser..
=========================
db_connect, anslut mot en databas
db_query, ställ en fråga
db_fetch_row, hämta en rad
db_execute_scalar, hämta _ett_ värde
GLOBALS["errormsg"], denna innehåller ett felmeddelande om någon funktion felar.
Exempel på hur den kan användas:
=========================
//Skapa en db förbindelse
if (!db_connect("localhost","testdb","userid","password")) die ("Could not connect to the database");
//Ställ en fråga
if (!db_query("SELECT name,email FROM user_info ORDER BY name")) die("Could not execute a query");
//Visa alla namn
while (db_fetch_row())
{
echo $rs["name"]."<br>";
}
//Visa antalet användare
echo "The number of users are: ".db_execute_scalar("select count(*) FROM user_info");
Klassen
======================================
//================================================
//
// Database Wrapper Class
//
// Version .: 1.0
// Author ..: Jonas Gauffin
// Date ....: 2002-08-15
// Homepage : http://jonas.gauffin.org/php
//
//================================================
$errormsg = "";
$db_id = -1;
$db_res_id = -1;
function db_connect($server, $db, $user, $pw)
{
if (!$GLOBALS["db_id"] = mysql_connect ($server, $user, $pw))
{
$GLOBALS["errormsg"] = "Could not connect to the database.";
return false;
}
if (!mysql_select_db($db))
{
$GLOBALS["errormsg"] = "Could not select the database.";
return false;
}
return $GLOBALS["db_id"];
}
function db_query($sql)
{
if (!$GLOBALS["db_res_id"] = mysql_query($sql))
{
$GLOBALS["errormsg"] = "Database query failed on ".$_SERVER["SCRIPT_NAME"];
return false;
}
return $GLOBALS["db_res_id"];
}
function db_fetch_row($resid = "")
{
if ($resid == "") $resid = $GLOBALS["db_res_id"];
return mysql_fetch_row($resid);
}
function db_execute_scalar($sql)
{
if (!$resid = mysql_query($sql))
{
$GLOBALS["errormsg"] = "Failed to execute sql";
return false;
}
if (!$rs = mysql_fetch_row($resid))
{
$GLOBALS["errormsg"] = "Failed to fetch data";
return false;
}
return $rs[0];
}