不知道原创要写到随笔里。
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必须和数据库的列名相同,否则你就白看这么多

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

In this article, we're going to explore the notification system in the Laravel web framework. The notification system in Laravel allows you to send notifications to users over different channels. Today, we'll discuss how you can send notifications ov


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 Chinese version
Chinese version, very easy to use

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

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