Hey. Her er en class til databasebrug
class database
{
private $connectlink; //Database Connection Link
private $username = "root";
private $password = "";
private $database = "databasenavn";
private $hostname = "localhost";
private $resultlink; //Database Result Recordset link
public $rows; //Stores the rows for the resultset
public $count; //Stores the row count for the requested table
function __construct()
{
$this->connectlink = mysql_connect($this->hostname,$this->username,$this->password);
if(!($this->connectlink))
{
//throw new DatabaseConnectionException("Error Connecting to the Database".mysql_error(),"101");
}
else
{
mysql_select_db($this->database);
}
}
function __destruct()
{
@mysql_close($this->connectlink);
}
public function query($sql)
{
$this->resultlink = mysql_query($sql);
return $this->resultlink;
}
public function fetch_rows($sql)
{
$result = $this->query($sql);
$rows = array();
if($result)
{
while($row = mysql_fetch_array($result))
{
$rows[] = $row;
}
}
else
{
//throw new RetrieveRecordsException("Error Retrieving Records".mysql_error(),"102");
$rows = null;
}
$this->rows = $rows;
return $this->rows;
}
public function count_rows($sql)
{
$count = $this->query($sql);
while ($row_count = mysql_fetch_array($count))
{
$count_row = $row_count;
$this->count_row = $count_row;
return $this->count_row;
}
}
}
?>
For at få adgang til databasen skriver du sådan:
<?php
require_once('STIEN TIL DATABASECLASS.php');
$db = new database();
?>
Derefter for at kalde noget:
$db->fetch_rows("SELECT ID, Username FROM usertable") or die(mysql_error());
$variabel = $db->rows[0][ID] // array der henter første entry i row "ID"
echo $variabel;
Hvis du derimod vil have flere entries:
$db->fetch_rows("SELECT ID, Username, COUNT(ID) FROM usertable") or die(mysql_error());
while ($i = 1; $rows[0]['COUNT(ID)'] >= $i; i++)
{
$login_Output[$i][0] = $rows[$i-1]['ID'];
$login_Output[$i][1] = $rows[$i-1]['Username'];
}
echo $login_Output[3][0];
echo $login_Output[3][1];
Hvis du vil hente flere på en gang og få alle vist:
$db->fetch_rows("SELECT ID, Username, COUNT(ID) FROM usertable") or die(mysql_error());
while ($i = 1; $rows[0]['COUNT(ID)'] >= $i; i++)
{
$login_Output[$i][0] = $rows[$i-1]['ID'];
$login_Output[$i][1] = $rows[$i-1]['Username'];
echo $login_Output[$i][0];
echo $login_Output[$i][1];
}
Hvis du går efter den simple metode:
$link = mysql_connect("localhost","username","password");
mysql_select_db("databasenavn", $link);
Det mest simple:
<?php
//Flere
mysql_connect("localhost", "root", "");
mysql_select_db("databoxme");
$query = mysql_query("Select * FROM phonebook");
while($row = mysql_fetch_array($query))
{
echo $row['ID'];
}
?>
<?php
//Enkel
mysql_connect("localhost", "root", "");
mysql_select_db("databoxme");
$query = mysql_query("Select * FROM phonebook");
$row = mysql_fetch_array($query);
echo $row['ID'];
?>
Tror ikke jeg har lavet fejl, men har ikke testet det.
Indlæg senest redigeret d. 28.03.2010 16:55 af Bruger #14181