How to connect to a Database from PHP
Thursday, January 3rd, 2008
A few days ago I posted a tutorial on How to connect to a Database from VB.Net, now I am showing you how to do the same with PHP.
The method I use is very similar to the one I use with VB, I have a class called db_interfase, and I create an object whenever I need to interact with the database.
-
class db_interfase
-
{
-
var $conn;
-
var $dataset;
-
-
function db_interfase($sql)
-
{
-
$this->executesql($sql);
-
}//db_interfase
-
-
function opendb()
-
{
-
$db_username="dbuser";
-
$db_password="dbpass";
-
$db_server="dbserver";
-
$db_database="db";
-
-
$this->conn = mysql_pconnect($db_server,$db_username,$db_password)or die ('Error connecting to mysql');
-
}//opendb
-
-
function executesql($sql)
-
{
-
$this->opendb();
-
$this->dataset = mysql_query($sql) or die('Error, query failed ' . $offset . $rowsperpage . mysql_error() . $sql );
-
}//executesql
-
-
}//Class
This is a live example, this code is running on Wiisteria.com
-
public function insert($user,$game,$fc)
-
{
-
$sql = "insert into usergames(user,game,fc) values($user,$game,$fc)";
-
-
$ds = new db_interfase($sql);
-
}//insert
The magic is done here
-
$ds = new db_interfase($sql);
There you create the db_interfase object with the query as the parameter, and then it returns a dataset ($ds) which you can manipulate whenever you see fit. That code also works for selects and updates, for example.
-
public function selectgamesbytitle($title)
-
{
-
$sql = "Select username from usergames ug join wifigames wfg on ug.game=wfg.game where wfg title = '$title' ";
-
-
$ds = new db_interfase($sql);
-
-
return $ds->dataset;
-
}//selectgamesbytitle
Then you could manipulate $ds like this.
The class can be downladed here, if you have questions just post them and Ill try to answer them.


