Simple PHP writing database class code sharing_PHP tutorial
I don’t know if originality should be included in the essay.
All right, first blog post.
There are three classes:
1. Filter input (lightweight)
class input_filter
is responsible for filtering parameters such as $_GET, $_POST.
The return value type is an array, using Parameters of made_sql class
2. Convert into SQL statement
class made_sql
The type of the parameters is array and table name (string), the key of the array is the column name of the table, and the value is the inserted value
The return value type is a string, which is used as a parameter of the mysql ->query method
3. Database query
class mysql
uses single column mode and uses static methods to obtain objects. For details, see instanceof operation The function of the symbol
class input_filter
{
private $input_all; // Array to be filtered
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';
//Initialization, otherwise the array will be merged for the first time PHP doesn’t know what type this 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, return an error message
// 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 replaced it with empty
$val_one = str_replace('#','',$val_input);
// This function only converts < > ' ", there is a similar function that will escape all symbols
$val = htmlspecialchars ($val_one,ENT_QUOTES,'UTF-8');
// merger
$rustle_one = array($key=>$val);
//merge array
$this-> ;rustle = array_merge($this->rustle,$rustle_one);
}
}
//This function is a bit redundant, leave it for future expansion
public function get_filter_rustle()
{
$this->filter_arr();
return $this->rustle ;
}
}
Calling method:
$filter = new filter_input($_GET); // or $_POST
$input_data = $filter- >get_filter();
Convert into SQL statement:
class madesql
{
private $Cnow_ary; // type array passed in parameters
private $Cname_str;
private $insert_sql; //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; // Written value
$this->Cname_str = $Cname; // Database table name
25 }
private function setSql() // Main Function, produces SQL statements
{
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 there is something wrong with the previous foreach algorithm, the first character It is a comma
// So use sunstr_replace() to delete, starting from the first character (0), only replace 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 shaping
}
//Extended use
public function getSql()
{
$this-> ;setSql();
return $this->insert_sql;
}
}
3. Database query
The database query class refers to the single column mode in the book (Use static methods to obtain objects, so that there is only one instance of the database query class in a script)
I think the singleton pattern is still useful for this class
class mysql
{
private $connect;
static $objectMysql; // Store the object
private function __construct() 7 {
//This when creating the object The constructor will be called to initialize
$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 the object belongs to an instance of a class or interface. What I said is not very standard...
//If $objectMysql is not an instance of mysql(self), then create one
if(! self::$objectMysql instanceof self)
self::$ objectMysql = new mysql();
//At this time, $objectMysql is already an object
return self::$objectMysql;
}
public function query($sql)
{
return mysql_query($sql,$this->db);
}
}
All right, summarize the usage
$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';
Only these are needed The operation of writing to the database can be completed by calling the code
In addition, let’s talk about the private and public issue of the constructor. In the mysql singleton mode in the book, the constructor is declared as private, and this will happen if there is no singleton mode. Compilation error, that is, PHP cannot create an object, checked.
The reason is that creating objects is often done outside the class, which creates the problem of inaccessible constructors. The single-column mode creates objects in its own class, so there are no restrictions on accessing private methods.
I originally thought that the singleton mode only prevents the creation of the same object. Now it seems that the singleton mode can encapsulate the constructor, which indeed improves security
The results of the filter_input class can be directly used as the madesql class The premise of the parameters is:
The name of the form must be the same as the column name of the database, otherwise you will see so much in vain

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.

In PHP, you can effectively prevent CSRF attacks by using unpredictable tokens. Specific methods include: 1. Generate and embed CSRF tokens in the form; 2. Verify the validity of the token when processing the request.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.
