Home Backend Development PHP Tutorial 简单的php写入数据库类代码分享_php技巧

简单的php写入数据库类代码分享_php技巧

May 17, 2016 am 09:16 AM

不知道原创要写到随笔里。
All right ,第一篇博文。
有三个类:
1 . 过滤输入(轻量级的)
class input_filter
负责将参数,如$_GET,$_POST 这些过滤
返回值类型为 数组,用作 made_sql 类的参数
2 . 转换成SQL语句
class made_sql
参数的类型为数组和表名(字符串),数组的键名为表的列名,值为插入值
返回值类型为 字符串 ,用作 mysql ->query方法 的参数
3 . 数据库查询
class mysql
用到了单列模式,用静态方法来获取对象,具体参看 instanceof操作符的作用

复制代码 代码如下:

class input_filter
{
private $input_all; // 要过滤的数组
private $rustle; // 过滤后的结果
//构造函数 参数可以是$_GET or $_POST 这些
public function __construct($input_C)
{
if(is_array($input_C))
$this->input_all = $input_C ;
else
echo 'Parameter is not valid';
//初始化,不然后面第一次合并数组PHP不知道这是什么类型
$this->rustle = array();
}
private function filter_arr() // 主函数
{
foreach ($this->input_all as $key_input => $val_input)
{
//如果键名不是字符串,那么返回错误信息
// 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');
// 我没找 # 的HTML转义符,所以用空代替
$val_one = str_replace('#','',$val_input);
// 这个函数只转化 ' " ,还有个类似函数会转义所有符号
$val = htmlspecialchars($val_one,ENT_QUOTES,'UTF-8');
// merger
$rustle_one = array($key=>$val);
//合并数组
$this->rustle = array_merge($this->rustle,$rustle_one);
}
}
//这个函数有点多余,留下以后扩展用
public function get_filter_rustle()
{
$this->filter_arr();
return $this->rustle ;
}
}

调用方法:
复制代码 代码如下:

$filter = new filter_input($_GET) ; // or $_POST
$input_data = $filter->get_filter();

转换成SQL语句:
复制代码 代码如下:

class madesql
{
private $Cnow_ary; // type array 传入的参数
private $Cname_str;
private $insert_sql; //最终的sql语句 string type
public function __construct($Cary,$Cname)
{
//检查传入参数类型是否为数组
if (! is_array($Cary))
return false;
else
$this->Cnow_ary = $Cary; // 写入的值
$this->Cname_str = $Cname; // 数据库表名称
25 }
private function setSql() // 主函数 ,生产SQL语句
{
foreach ( $this->Cnow_ary as $key_ary => $val_ary )
{
$cols_sql = $cols_sql.','.$key_ary; //列名组合
$vals_sql = $vals_sql.', \''.$val_ary.'\'' ; //值 组合
}
// 因为前面foreach的算法有点问题,第一个字符是逗号
// 所以用sunstr_replace()删除 ,自第一位起(0),只替换一个字符(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.' )'; // 语句成型
}
//扩展用
public function getSql()
{
$this->setSql();
return $this->insert_sql;
}
}

3 . 数据库查询
数据库查询类是参照书上的单列模式(用静态方法获取对象,这样在一个脚本里只有一个数据库查询类的实例)
我想单例模式用于这个类还是有点用的
复制代码 代码如下:

class mysql
{
private $connect;
static $objectMysql; // 存放对象
private function __construct() 7 {
// 创建对象的时候这个构造函数会被调用,用来初始化
$connect = mysql_connect('db address','password','dbname');
$this->db = mysql_select_db('db',$connect);
}
public static function Mysql_object()
{
//instanceof 操作符用于检查对象是否属于某个类或者接口的实例。我说的不是很规范...
//如果$objectMysql不是mysql(self)的实例,那么就创建一个
if(! self::$objectMysql instanceof self)
self::$objectMysql = new mysql();
//这时候的$objectMysql就已经是一个对象
return self::$objectMysql;
}
public function query($sql)
{
return mysql_query($sql,$this->db);
}
}
  

All right ,归纳一下使用方法
复制代码 代码如下:

$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';

只需要这几行调用代码即可以完成写入数据库的操作
另外再说一下构造函数的私有公有问题,书上的mysql单例模式中构造函数是声明为了private ,而没有单例模式的类如此则会产生编译错误,即 PHP 不能创建一个对象 ,查了下。

原因在于创建对象往往在类外面进行,这样就产生了无法访问构造函数的问题。 而单列模式是在自身类中创建对象,因此访问private方法没有限制。

原先以为单例模式只是防止创建相同的对象,现在看来单例模式可以将构造函数封装起来,确实提高了安全性
  filter_input类 的结果可以直接用作 madesql类 的参数的 前提是 :
表单的name必须和数据库的列名相同,否则你就白看这么多
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

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,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

See all articles