PHP中批量插入多条记录到数据表

 

 

class test {
    /**
     * 获取插入的数据SQL
     *
     * @author wengxianhu
     * @created to 2013-05-27
     * @param unknown $data
     * @return multitype:
     */
    public function _getInsertInfo($data)
    {
        reset($data);
        $fields = array();
        $values = array();
        $length = 1;
        if (key($data) === 0 && is_array($data[0]))
        {
            $length = count($data);
            foreach ($data as $_k => $_v)
            {
                foreach ($_v as $_f => $_fv)
                {
                    $is_array = is_array($_fv);
                    ($_k == 0 && !$is_array) && $fields[] = '`'.$_f.'`';
                    !$is_array && $values[$_k][] = "'". addslashes(stripslashes($_fv)) . "'";
                }
                $values[$_k] = '(' . implode(',', $values[$_k]) . ')';
            }
        }
        else
        {
            foreach ($data as $_k => $_v)
            {
                $is_array = is_array($_v);
                !$is_array && $fields[] = '`'.$_k.'`';
                !$is_array && $values[] = "'" . addslashes(stripslashes($_v)) . "'";
            }
            $values = '(' . implode(',', $values) . ')';
        }
        $fields = '(' . implode(',', $fields) . ')';
        is_array($values) && $values = implode(',', $values);
        return compact('fields', 'values', 'length');
    }

    /**
     * 批量插入数据
     *
     * @author wengxianhu
     * @created to 2013-05-27
     * @param unknown $set
     * @param string $table 表名
     */
    public function insertAll($set, $table)
    {
        $insert_info = $this->_getInsertInfo($set);
        $sql = "INSERT INTO {$table} {$insert_info['fields']} VALUES{$insert_info['values']}";
        $this->query($sql,'execute');//这里根据当前使用的系统修改
    }
}
$goods = array(
    array('goods_id'=>2000,'cate_id'=>100,'name'=>'godos1'),
    array('goods_id'=>2001,'cate_id'=>101,'name'=>'godos2'),
    array('goods_id'=>2002,'cate_id'=>102,'name'=>'godos3'),
);
// $goods = array('goods_id'=>2000,'cate_id'=>100,'name'=>'godos1');
$a = new test();
$a->insertAll($goods, 'ecm_goods');

 

你可能感兴趣的:(批量插入)