pdo之增删改查(修改版,无预处理)

pdo = new PDO($dsn,$user,$pass,array(PDO::ATTR_PERSISTENT =>true)); //持久化连接
    }

    /**
     * 过滤表中不存在的字段;用于update,insert方法;
     * @param $tableName
     * @param $data
     * @return mixed
     */
    function filterTableColumn($tableName,$data)
    {
        $sql = "SELECT column_name FROM information_schema.`COLUMNS` WHERE table_name='{$tableName}' AND table_schema = '{$this->dbInfo['databaseName']}'";
        $result = $this -> pdo ->query($sql);
        $columns=$result->fetchAll(PDO::FETCH_ASSOC);
        $fields = array();
        foreach ($columns as $column) {
            $fields[] = $column['column_name'];
        }
        //字段在对应表中不存在,则删除该字段;
        foreach ($data as $key => $value) {
            if (!in_array($key,$fields)) {
                unset($data[$key]);
            }
        }
        return $data;
    }

    public function query($sql)
    {
        $queryResult =$this -> pdo -> exec($sql); //常用于insert update 操作;同lastInsertId 一起使用;

        $this -> insertID = $this -> pdo ->lastInsertId();
        $this -> affectedRows = $queryResult;
        return $queryResult;
    }

    function getNumRows($sql)
    {
        $recordSet = array();
        $sql = strtolower($sql);
        $fromsql = explode('from', $sql);
        $sql = 'select count(*) as num from'.$fromsql[1];
        $tempSql = explode('limit',$sql);
        $sql = $tempSql[0];
        $rsArr = $this -> pdo ->query($sql);
        if($rsArr){
            $recordSet = $rsArr -> fetchAll(PDO::FETCH_ASSOC);
        }
        return $recordSet[0]['num'];
    }

    function insertIntoOneRecord($tableName,$dataArray)
    {
        $fieldArray = array();
        $valueArray = array();
        $dataArray = $this->filterTableColumn($tableName,$dataArray);
        foreach ($dataArray as $key => $value){
            if($value != ''){
                $fieldArray[] = "`".$key."`";
                $valueArray[] = "'".addslashes($value)."'";
            }
        }

        $sql = "INSERT INTO `".$tableName."` 
				( ".implode(',', $fieldArray)." )
				VALUES
				( ".implode(',', $valueArray)." )";
        //echo $sql;
        $result = $this -> query($sql);
        //echo '$result='.$result;
        return $result;
    }

    function updateOneRecord($tableName,$dataArray,$whereArray)
    {
        $dataArray = $this->filterTableColumn($tableName,$dataArray);
        $setArray = array();
        $where = array();
        foreach ($dataArray as $key => $value){

            if(isset($value) && $value != '' ){
                $setArray[] = "`".$key."` = '".addslashes($value)."'";
            }
            if ($key == 'note' && $value == null) {
                $setArray[] = "`note` = ''";
            }
        }

        foreach ($whereArray as $key => $value){
            $where[]= "`".$key."` = '".addslashes($value)."'";
        }

        $sql = "UPDATE `".$tableName."` 
				SET
				".implode(',', $setArray)."
				WHERE
				".implode(' AND ', $where);
        $result = $this->query($sql);
        return $result;
    }

    function deleteOneRecord($tableName,$whereArray)
    {
        $where = array();
        foreach ($whereArray as $key => $value){
            $where[] ="`".$key."` = '".addslashes($value)."'";
        }
        $sql = "DELETE FROM `".$tableName."` 
				WHERE
				".implode(' AND ', $where);
        //echo $sql;exit;
        $result = $this->query($sql);
        return $result;
    }

    public function getOne()
    {
        $result = $this->pdo->query($sql); //返回一个有结果集的对象,常用于查询;
        if ($result) {
            $rs = $result->fetch(PDO::FETCH_ASSOC); //获取一条数据,关联索引;
        }
        return $rs; 
    }

    public function doSelect($sql)
    {
        $result = $this->pdo->query($sql); //返回一个有结果集的对象,常用于查询;
        if ($result) {
            $rs = $result->fetchAll(PDO::FETCH_ASSOC); 
        }
        return $rs;
    }
}

总结经验;

1.PDO常用方法:

  • PDO::query()主要用于有记录结果返回的操作(PDOStatement),特别是select操作。
  • PDO::exec()主要是针对没有结果集合返回的操作。如insert,update等操作。返回影响行数。
  • PDO::lastInsertId()返回上次插入操作最后一条ID,
    但要注意:如果用insert into tb(col1,col2) values(v1,v2),(v11,v22)…的方式一次插入多条记录,
    lastinsertid()返回的只是第一条(v1,v2)插入时的ID,而不是最后一条记录插入的记录ID。
  • PDOStatement::fetch()是用来获取一条记录。配合while来遍历。
  • PDOStatement::fetchAll()是获取所有记录集到一个中。
    2.fetch 和 fetchAll参数选择;
  • row=row=rs->fetchAll(PDO::FETCH_BOTH); FETCH_BOTH是默认的,可省,返回关联和索引。
  • row=row=rs->fetchAll(PDO::FETCH_ASSOC); FETCH_ASSOC参数决定返回的只有关联数组。
  • row=row=rs->fetchAll(PDO::FETCH_NUM); 返回索引数组
  • row=row=rs->fetchAll(PDO::FETCH_OBJ); 如果fetch()则返回对象,如果是-fetchall(),返回由对象组成的二维数组

你可能感兴趣的:(PHP,pdo)