Simple PHP Database Processing class

Source: Internet
Author: User
Tags foreach php and php database rtrim string format


Recently looking at the backing network of PHP video, the main content is related to the production of a blog system, the feeling is still very rewarding.

A simple database processing class

Here is a simple database processing class, see source code:

The code is as follows Copy Code
<?php
/**
* Created by JetBrains Phpstorm.
* User:yangliu
* DATE:2013-7-12
* Time: 6:19
* Description: This is a simple database operation class, easy to quickly insert data into the database, delete data, update data
*/
Class DB {
Database connection
protected $mysqli;
Table name
protected $table;
Options
protected $opt;
/***
* Construction Method
* @param $tab _name
*/
function __construct ($tab _name) {
$this->config ($tab _name);
}

Configuration method
Protected function config ($tab _name) {
$this->db=new mysqli (dbhost,dbuser,dbpwd,dbname);
Dbfix for database table prefixes
$this->table = dbfix. $tab _name;
if (Mysqli_connect_errno ()) {
echo "Database connection Error". Mysqli_connect_errno ();
Exit ();
}
$this->db->query ("SET NAMES ' GBK '");

Set an initial value for an opt array
$this->opt[' field '] = ' * ';
$this->opt[' where ']= $this->opt[' order ']= $this->opt[' limit ']= $this->opt[' group '] = ';
}

Get Current table field
function Tbfields () {
$result = $this->db->query ("DESC {$this->table}");
$FIELDARR = Array ();
while (($row = $result->fetch_assoc ())!=false) {
$FIELDARR [] = $row [' Field '];
}
return $FIELDARR;
}

Get query fields
function field ($field) {
$FIELDARR = is_string ($field) Explode (",", $field): $field;
if (Is_array ($FIELDARR)) {
$field = ';
foreach ($fieldArr as $v) {
$field. = "". $v. " ',';
}
}
return RTrim ($field, ', ');
}

SQL Conditional method
function where ($where) {
$this->opt[' where '] = is_string ($where)? " WHERE ". $where: ';
return $this;
}

Limit method
function Limit ($limit) {
$this->opt[' limit '] = is_string ($limit)? "LIMIT". $limit: ';
return $this;
}

Sorting method
function Order ($order) {
$this->opt[' order '] = is_string ($order)? "Order BY". $order: ';
return $this;
}

Grouping GROUP BY
Function Group ($group) {
$this->opt[' group '] = is_string ($group)? ' GROUP by '. $group: ';
return $this;
}

SELECT
function Select () {
$sql = ' Select {$this->opt[' field '} from {$this->table}
{$this->opt[' where ']} {$this->opt[' group ']} {$this->opt[' limit ']}
{$this->opt[' order ']} ";
return $this->sql ($sql);
}

Delete method
function Delete ($id = ' ") {
if ($id = = ' && empty ($this->opt[' where ')) {
Die (' query condition cannot be empty ');
}
if ($id!= ') {
if (Is_array ($id)) {
$id = Implode (', ', $id);
}
$this->opt[' where '] = "where ID in (". $id. ")";
}
$sql = "DELETE from {$this->table} {$this->opt[' where ']} {$this->opt[' limit ']}";
echo $sql. " <br/> ";
return $this->query ($sql);
}

Check a single record
function Find ($id) {
$sql = "Select {$this->opt[' field ']} from {$this->table} WHERE ' id ' = {$id}";
echo $sql. ' <br> ';
return $this->sql ($sql);
}

Add data
function Insert ($args) {
Is_array ($args) or Die (' parameter not array ');
$fields = $this->field (Array_keys ($args));
$values = $this->values (array_values ($args));
$sql = "INSERT into {$this->table} ({$fields}) VALUES ($values)";
if ($this->query ($sql) >0) {
return $this->db->insert_id;
}
return false;
}

Updating update
function Update ($args) {
Is_array ($args) or Die ("parameter is not an array");
if (Empty ($this->opt[' where ')) die ("condition cannot be null");
$set = ';
$GPC = GET_MAGIC_QUOTES_GPC ();
while (the list ($k, $v) = each ($args)) {
$v =! $GPC addslashes ($v): $v;
$set. = "' {$k} ' = '". $v. "', ';
}
$set = RTrim ($set, ', ');
$sql = "UPDATE {$this->table} SET $set {$this->opt[' where ']}";
return $this->query ($sql);
}

Statistics of all records
function count ($tabname = ' ") {
$tabname = $tabname = = "? $this->table: $tabname;
$sql = "Select ' id ' from {$tabname} {$this->opt[' where ']}";
echo $sql. ' <br/> ';
return $this->query ($sql);
}

The data array is converted to string format.
protected function values ($value) {
if (! GET_MAGIC_QUOTES_GPC ()) {
$strValue = ';
foreach ($value as $v) {
$strValue. = "'". Addslashes ($v). "',";
}
} else {
foreach ($value as $v) {
$strValue. = "' $v '";
}
}
return RTrim ($strValue, ', ');
}

Get result set
function SQL ($sql) {
$result = $this->db->query ($sql) or Die ($this->dberror ());
$RESULTARR = Array ();
while (($row = $result->fetch_assoc ())!=false) {
$RESULTARR [] = $row;
}
return $RESULTARR;
}

SQL with no result set
function query ($sql) {
$this->db->query ($sql) or Die ($this->dberror ());
return $this->db->affected_rows;
}

return error
function Dberror () {
return $this->db->error;
}
}
?>

The above is a simple PHP database processing class, on its use specifically?? The?/p> of the chaos

The following is a description of the partial phase constants and variables in the above code:

$mysqli: A link reference to the current database
$table: Table name for the current database
$opt: All field names for tables in the current database
Dbfix: Constant "table prefix" in database configuration
Dbhost: Database Host
Dbfix: Database user name
DBPWD: Database Password
dbname: Database name

How to use database processing classes
Configure Database Processing classes

Before using the database processing class, you must have a related configuration file, and I'll write a connect.php file below. The contents of the file are as follows:

  code is as follows copy code
   <?php
   /**
    * Created by JetBrains Phpstorm.
    * User:yangliu
    * date:2013-7-14
    * Time: PM 2:15
    * Description: Database configuration file
    */
    define ("Dbhost", ' localhost '); Define database Server connection address
    define ("Dbuser", ' root ');//database user name
    define ("Dbpwd", ""); /Database Password
    define ("dbname", ' blog ');//define database name
    define ("Dbfix", ' Blog_ '); Define the prefix of the database table
   

To make it easier for you to understand, I didn't build more directories and put all the files in the same directory. If you feel bad, you can also set up your own table of contents and rearrange the file locations according to the situation.
Use of database processing classes

To use a database, you first refer to connect.php and db.class.php files. Here's an example of a demo.php file:

  code is as follows copy code

     <?php
   /**
    * Created by JetBrains Phpstorm.
     * User:liuyang
    * date:2013-9-15
    * Time: PM 10:39
 &nb sp;  * Description: Demo demo file
    */
    include './config.php ';//load configuration file
    include './page.class.php '; Load database processing class
    
    $db = $db = new db (' blog ');//Link database table Blog_blog
     
   

The field name of the Output database table

The field name of the output database table, using the Tbfields method. The code is as follows:

The code is as follows Copy Code

$tbField = $db->tbfields ();
Var_dump ($tbField);

The output results are as follows:

Array (size=5)
0 => string ' id ' (length=2)
1 => string ' Btitle ' (length=6)
2 => string ' content ' (length=7)
3 => string ' status ' (length=6)
4 => string ' cid ' (length=3)

Here's another way to relate to a database-processing class:

echo $db->field ($tbFields);

Final output: ' id ', ' btitle ', ' content ', ' status ', ' CID '
Statistics of all records

There is also a method in the database class that counts the count method for all the number of bars in the data. In our paging process, it is also important to show.

The code is as follows Copy Code
echo $db->count (' blog ');

Note: The above code is checked against the ID. Where the Count method code is as follows:

The code is as follows Copy Code
Statistics of all records
function count ($tabname = ' ") {
$tabname = $tabname = = "? $this->table: $tabname;
$sql = "Select ' id ' from {$tabname} {$this->opt[' where ']}";
return $this->query ($sql);
}

increase, deletion, modification and investigation of database

The relevant operation of the database is to increase, delete, change, check. Here's a brief introduction to it:
Inserting data

The Insert method inserts data into the database, where the arguments passed are an array, such as Array (' Btitle ' => ' www.111cn.net ', ' content ' => ' a niche, the world is a technical Exchange blog '). The key name of the array is the field name of the table, and the key value is the content that you want to insert. Take a look at the following example:

The code is as follows Copy Code

$INSERARR = Array (' btitle ' => ' www.111Cn.net ', ' content ' => ' world, the world is a technical Exchange blog ');
$db->insert ($INSERARR);

Delete data

The Delete method is designed to delete data. In order to prevent the data from being mistakenly deleted, there must be some restrictions on data deletion. For example, use a where, limit method to make certain restrictions, or you can pass directly to delete the data ID. You can view the following example:

The code is as follows Copy Code
Delete Data with ID 3
$db->delete (3);

To delete id>5 data
$db->where (' id>5 ')->delete ();

Delete 10 data from 20
$db->where (' id>5 ')->limit (' 20,10 ')->delete ();

Update data

Data is added, and sometimes errors are found, and they are high enough to change the data. The Update method is used to update data. The Update method, like the Insert method, takes an array parameter: The array's key name is the field name of the table, and the corresponding key value is the content to be inserted. The following is to update the ID 29 data to the data in the array.

The code is as follows Copy Code
$db->where (' id=29 ')->update (' Btitle ' => ' www.111cn.net ', ' content ' => ' world, the world is a Technology Exchange blog '));
Update all data for id>35
$db->where (' id>29 ')->update (' Btitle ' => ' www.111cn.Net ', ' content ' => ' world, the world is a Technology Exchange blog '));

Find data

The Select method is provided in the database processing class, which makes it easy to find the data. Combining the where and limit methods, you can find the appropriate data. For specific use, see the following example:

The code is as follows Copy Code
$db->select (); Find all data

$db->where (' id=0 ')->select (); Find specified data

$db->where (' id>9 ')->select (); Lookup data collection with ID greater than 9

$db->limit (' 10,9 ')->select (); 9 data after finding the data from article 10th

$db->where (' id>50 ')->limit (' 10,9 ')->select ();

Other methods

In addition to the above methods, the database processing classes provide the following methods.

Order method: Primarily to change the way the lookup data is sorted
Group method: Array method
Find method: Finding a single record
SQL method: Executes the data SQL statement directly and returns the data set at
Query method: You can also execute a data SQL statement but not return a dataset, but instead return the number of affected record bars

About database Processing classes

Finally, this database processing class is backed up by the network PHP video, to help like me as a novice (that is, I) to learn, so specially sorted.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.