欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

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

程序员文章站 2022-05-05 13:48:06
...
  1. $mysql = new sqlstr("table1");
  2. $mysql->set("name","value");
  3. $mysql->set("name","1",true);
  4. echo $mysql->insertSql();
复制代码

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

  1. /**
  2. * Insert、Update语句的构造类
  3. * edit: bbs.it-home.org
  4. */
  5. class sqlstr
  6. {
  7. private $param=array();
  8. private $tablename;
  9. function sqlstr($tablename)
  10. {
  11. $this->tablename = $tablename;
  12. }
  13. public function set($name,$value,$isnum=false){
  14. $value = str_replace("'","''",$value);
  15. $this->param[$name]=array($value,$isnum);
  16. }
  17. public function insertSql(){
  18. $keys="";
  19. $values="";
  20. foreach($this->param as $key =>$value){
  21. $keys = $keys . $key . ",";
  22. if($value[1]){
  23. $values = $values . $value[0] . ",";
  24. }else{
  25. $values = $values . "'" . $value[0] . "',";
  26. }
  27. }
  28. if($keys!=""){$keys=substr($keys,0,strlen($keys)-1) ;}
  29. if($values!=""){$values=substr($values,0,strlen($values)-1) ;}
  30. return "insert into " .$this->tablename ."($keys) values($values)";
  31. }
  32. public function updateSql($cond){
  33. $group="";
  34. foreach($this->param as $key =>$value){
  35. $group .= $key . "=";
  36. if($value[1]){
  37. $group.= $value[0] . ",";
  38. }else{
  39. $group.= "'" . $value[0] . "',";
  40. }
  41. }
  42. if($group!=""){$group=substr($group,0,strlen($group)-1) ;}
  43. return "update " . $this->tablename ." set $group where " . $cond;
  44. }
  45. }
复制代码