PHP中使用Insert、Update语句的构造类

发布时间:2020-11-06编辑:脚本学堂
本文分享一个使用insert、update语句实现的php构造类,有兴趣研究mysql中insert与update操作的方法,可以参考学习下。

很简单的一段代码,学习下使用Insert和Update语句实现构造类的方法。

1,调用方法
 

复制代码 代码示例:
<?php
$mysql = new sqlstr("table1");
$mysql->set("name","value");
$mysql->set("name","1",true);
echo $mysql->insertSql();

2,insert与update实现的php构造类
 

复制代码 代码示例:
<?php
/**
* Insert、Update语句的构造类
* edit: www.jb200.com
*/
class sqlstr
{
private $param=array();
private $tablename;
function sqlstr($tablename)
{
$this->tablename = $tablename;
}
public function set($name,$value,$isnum=false){
$value = str_replace("'","''",$value);
$this->param[$name]=array($value,$isnum);
}
public function insertSql(){
$keys="";
$values="";
foreach($this->param as $key =>$value){
$keys = $keys . $key . ",";
if($value[1]){
$values = $values . $value[0] . ",";
}else{
$values = $values . "'" . $value[0] . "',";
}
}
if($keys!=""){$keys=substr($keys,0,strlen($keys)-1) ;}
if($values!=""){$values=substr($values,0,strlen($values)-1) ;}
return "insert into " .$this->tablename ."($keys) values($values)";
}
public function updateSql($cond){
$group="";
foreach($this->param as $key =>$value){
$group .= $key . "=";
if($value[1]){
$group.= $value[0] . ",";
}else{
$group.= "'" . $value[0] . "',";
}
}
if($group!=""){$group=substr($group,0,strlen($group)-1) ;}
return "update " . $this->tablename ." set $group where " . $cond;
}
}