This article describes the PHP surface Image Object database operation class. Share to everyone for your reference.
The specific implementation code is as follows:
Copy Code code as follows:
A database operation class is constructed here to encapsulate all database operations
can be extended to facilitate the use of background management programs
Class MySQLdb
{
var $host;
var $user;
var $passwd;
var $database;
var $conn;
Initialize a variable with a constructor implementation
Connecting to database operations at the same time
function MySQLdb ($host, $user, $password, $database)
{
$this->host = $host;
$this->user = $user;
$this->passwd = $password;
$this->database = $database;
$this->conn=mysql_connect ($this->host, $this->user, $this->passwd) or
Die ("Could not connect to $this->host");
mysql_select_db ($this->database, $this->conn) or
Die ("Could not switch to database $this->database");
}
This function is used to close the database connection
function Close ()
{
Mysql_close ($this->conn);
}
This function implements database query operation
function Query ($QUERYSTR)
{
$res =mysql_query ($queryStr, $this->conn) or
Die ("Could not query database");
return $res;
}
This function returns the recordset
function GetRows ($res)
{
$rowno = 0;
$rowno = mysql_num_rows ($res);
if ($rowno >0)
{
for ($row =0; $row < $rowno; $row + +)
{
$rows [$row]=mysql_fetch_array ($res);
Originally mysql_fetch_row, but cannot be extracted as an array, only indexed
This makes it easier to use indexes and names.
}
return $rows;
}
}
This function retrieves the number of database records
function Getrowsnum ($res)
{
$rowno = 0;
$rowno = mysql_num_rows ($res);
return $rowno;
}
This function returns the number of database table fields
function Getfieldsnum ($res)
{
$fieldno = 0;
$fieldno = Mysql_num_fields ($res);
return $fieldno;
}
This function returns the database table field name set
function GetFields ($res)
{
$FNO = $this->getfieldsnum ($res);
if ($fno >0)
{
for ($i =0; $i < $fno; $i + +)
{
$fs [$i]=mysql_field_name ($res, $i);//Take the name of the first field
}
return $FS;
}
}
}
Require the file directly when used, and then instantiate:
$SqlDB = new MySQLdb ("localhost", "root", "root", "TestDB");
$sql = "SELECT * from TableX ...";
$result = $SqlDB->query ($sql);//Query
$rs = $SqlDB->getrows ($result);//Get Recordset
$num = $SqlDB->getrowsnum ($result)//number of records obtained
... The rest of the operation is to loop the value,
for ($i =0; $i < $num; $i + +) {
Echo ($rs [$i] [field name]);
}
...
Finally, don't forget to close the data path connection
Copy Code code as follows:
Of course, this sentence can not, PHP will automatically log off! But this can develop a good habit, it is best to add! Other analogy.
I hope this article will help you with your PHP programming.