Simple PHP Write database class code sharing _php Tips

Source: Internet
Author: User
Do not know the original to write in the essay.
All right, the first blog post.
There are three classes:
1. Filter input (Lightweight)
Class Input_filter
Responsible for the filtering of parameters such as $_get,$_post
Returns the array of value types used as parameters for the Made_sql class
2. Convert to SQL statement
Class Made_sql
The type of the parameter is the array and table name (string), and the array's key name is the column name of the table, and the value is the inserted value
Returns the value type as a string, as a parameter to the MySQL->query method
3. Database query
Class MySQL
Using a single-column mode, the static method to obtain the object, see the role of the instanceof operator
Copy Code code as follows:

Class Input_filter
{
Private $input _all; The array to filter
Private $rustle; Filtered Results
Constructor parameters can be $_get or $_post these
Public function __construct ($input _c)
{
if (Is_array ($input _c))
$this->input_all = $input _c;
Else
Echo ' Parameter is not valid ';
Initialize, otherwise merge the array for the first time PHP doesn't know what this type is.
$this->rustle = Array ();
}
Private Function Filter_arr ()//main function
{
foreach ($this->input_all as $key _input => $val _input)
{
If the key name is not a string, then an error message is returned
For key
if (!is_string ($key _input))//Error
{
Echo ' This key is not string ';
return false;
}
The # is MySQL note.
$key _one = str_replace (' # ', ', ', $key _input);
$key = Htmlspecialchars ($key _one,ent_quotes, ' UTF-8 ');
I didn't find the HTML escape character for #, so I used null instead
$val _one = str_replace (' # ', ', ', $val _input);
This function only converts < > ' ", and a similar function escapes all symbols
$val = Htmlspecialchars ($val _one,ent_quotes, ' UTF-8 ');
Merger
$rustle _one = Array ($key => $val);
Merging arrays
$this->rustle = Array_merge ($this->rustle, $rustle _one);
}
}
This function is a bit redundant, leaving later to expand with
Public Function Get_filter_rustle ()
{
$this->filter_arr ();
return $this->rustle;
}
}

Call Method:
Copy Code code as follows:

$filter = new Filter_input ($_get); or $_post
$input _data = $filter->get_filter ();

Convert to SQL statement:
Copy Code code as follows:

Class Madesql
{
Private $Cnow _ary; Parameter passed in type array
Private $Cname _str;
Private $insert _sql; The final SQL statement string type
Public function __construct ($Cary, $Cname)
{
Check whether the incoming parameter type is an array
if (! Is_array ($Cary))
return false;
Else
$this->cnow_ary = $Cary; The value written
$this->cname_str = $Cname; database table name
25}
Private Function SetSQL ()//main function, production SQL statement
{
foreach ($this->cnow_ary as $key _ary => $val _ary)
{
$cols _sql = $cols _sql. ', '. $key _ary; Column name combination
$vals _sql = $vals _sql. '. $val _ary. \'' ; Value Combination
}
Because the previous foreach algorithm has a problem, the first character is a comma
So remove with Sunstr_replace (), starting from the first digit (0), replacing only one character (1)
$cols _sql = Substr_replace ($vals _sql, ', 0, 1);
$vals _sql = Substr_replace ($vals _sql, ', 0, 1);
$this->insert_sql =
' INSERT into '. $this->cname_str. '
. $cols _sql. ') VALUES ('. $vals _sql. ') '; Statement Molding
}
Extended with
Public Function GetSQL ()
{
$this->setsql ();
return $this->insert_sql;
}
}

3. Database query
A database query class is a single-column pattern on a reference book (a static method gets the object, so that there is only one instance of the database query class in a script)
I think a single case pattern is useful for this class.
Copy Code code as follows:

Class MySQL
{
Private $connect;
Static $objectMysql; Storing objects
Private Function __construct () 7 {
This constructor is invoked when the object is created to initialize the
$connect = mysql_connect (' DB address ', ' password ', ' dbname ');
$this->db = mysql_select_db (' db ', $connect);
}
public static function Mysql_object ()
{
The instanceof operator is used to check whether an object belongs to a class or an instance of an interface. What I'm saying is not very normative ...
If $objectmysql is not an instance of MySQL (self), create a
if (! Self:: $objectMysql instanceof Self)
Self:: $objectMysql = new MySQL ();
The $objectmysql is already an object.
Return self:: $objectMysql;
}
Public Function query ($sql)
{
Return mysql_query ($sql, $this->db);
}
}
  

All right, sum up the use method
Copy Code code as follows:

$filter = new Filter_input ($_get); or $_post
$input _data = $filter->get_filter ();
$MADESQL = new Madesql ($input _data, ' tablename ');
$sql = $madeSql->getsql ();
$mysql = Mysql::mysql_object ();
if ($mysql->query ($sql))
Echo ' Ok ';
Else
echo ' failure ';

You need only these lines of calling code to complete the operation of writing to the database
In addition to the private public problems of the constructor, the MySQL single example schema in the book is a constructor declared for private, but not a single instance of a class that produces a compilation error, that is, PHP cannot create an object and check it out.

The reason is that the creation of objects is often done outside the class, causing problems that cannot be accessed by constructors. A single-column mode creates an object in its own class, so there is no restriction on accessing the private method.

The fact that the single case pattern was supposed to prevent the creation of the same object now seems to encapsulate the constructor in a single case pattern, which does improve security
The result of the Filter_input class can be used directly as a parameter to the Madesql class if:
The name of the form must be the same as the column name of the database, otherwise you will see so much

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.