php 把csv文件导入到mysql数据库

 更新时间:2016年11月25日 16:39  点击:1523
本程序实现数据导入原理是先把csv文件上传到服务器,然后再通过php的fopen与fgetcsv文件把数据保存到数组,然后再用while把数据一条条插入到mysql数据库
 代码如下 复制代码
$fname = $_files['myfile']['name'];
$do = copy($_files['myfile']['tmp_name'],$fname);
if ($do){
echo"导入数据成功<br>";
}else{
echo "";
}

 

 代码如下 复制代码

error_reporting(0);// 导入csv格式的文件
$connect=mysql_connect("localhost","root","") or die("could not connect to database");
mysql_select_db("gklqtzcx",$connect) or die (mysql_error());
mysql_query("set names 'gbk'");
$fname = $_files['myfile']['name'];
$handle=fopen("$fname","r");
while($data=fgetcsv($handle,10000,",")){
$q="insert into records (name,classes,a_time,college,notify,receiver,r_time,handler) values ('$data[1]','$data[2]','$data[3]','$data[4]','$data[5]','$data[6]','$data[7]','$data[8]')";
mysql_query($q) or die (mysql_error());
}
fclose($handle);
echo "<meta http-equiv="refresh" content="1;url=list.php">1秒钟转入列表页,请稍等."

?>
<form enctype="multipart/form-data" action="<?php echo"".$_server["php_self"].""; ?>" method="post">
<p>导入cvs数据 <input name="myfile" type="file"> <input value="提交" type="submit">
</p>
</form>

本款php连接mysql数据库连接程序代码是一款比较简单实用的连接代码,希望本教程对各位同学会有所帮助哦。
 代码如下 复制代码

class mysql {
      public $sqlserver = 'localhost';
      public $sqluser = 'root';
      public $sqlpassword = '';
      public $database;

      public $last_query = '';

      private $connection;
      private $query_result;

      public function __construct() {}

      public function __destruct() {
       $this->close();
      }

    //+======================================================+
    // create a connection to the mysql database
    //+======================================================+
    public function connect($server = null, $user = null, $password = null, $database = null){
     if (isset($server)) $this->sqlserver = $server;
     if (isset($user)) $this->sqluser = $user;
     if (isset($password)) $this->sqlpassword = $password;
     if (isset($database)) $this->database = $database;

    $this->connection = mysql_connect($this->sqlserver, $this->sqluser, $this->sqlpassword);
    if($this->connection){
    if (mysql_select_db($this->database)){
    return $this->connection;
    }else{
    return $this->error();
    }
    }else{
    return $this->error();
    }
    }
    //+======================================================+
    // execute a query
    //+======================================================+
    public function query($query, $die = false){
      if ($query != null){
       $this->last_query = $query;
       $this->query_result = mysql_query($query, $this->connection);
       if(!$this->query_result){
        if ($die) die("die: ".$this->query_result);
        return $this->error();
       }else{
        if ($die) die("die: ".$this->query_result);
        return $this->query_result;
       }
      }else{
       echo "empty query cannot be executed!";
      }
    }
    //+======================================================+
    // returns the result
    //+======================================================+
    public function getresult(){
       return $this->query_result;
    }
    //+======================================================+
    // returns the connection
    //+======================================================+
    public function getconnection(){
       return $this->connection;
    }
    //+======================================================+
    // returns an object with properties rep
    //     resenting the result fields www.111cn.net and values
    //+======================================================+
    public function getobject($qry = null){
     if (isset($qry)) $this->query($qry);
     return mysql_fetch_object($this->getresult());
    }
    //+======================================================+
    // returns an array with keys representi
    //     ng the result fields and values
    //+======================================================+
    public function getarray($query_id = ""){
      if($query_id == null){
       $return = mysql_fetch_array($this->getresult());
      }else{
       $return = mysql_fetch_array($query_id);
      }
      return $return ? $return : $this->error();
    }
    //+======================================================+
    // returns the number of rows in the res
    //     ult
    //+======================================================+
      public function getnumrows($qry = null){
       if (isset($qry)) $this->query($qry);
       $amount = mysql_num_rows($this->getresult());
       return empty($amount) ? 0 : $amount;
    }
    //+======================================================+
    // returns if the result contains rows
    //+======================================================+
    public function hasresults($qry = null) {
      if (isset($qry)) $this->query($qry);
     return $this->getnumrows($qry) > 0;
    }
    //+======================================================+
    // returns the number of rows that where
    //     affected by the last action
    //+======================================================+
    public function getaffectedrows($qry = null, $query_id = null){
      if (isset($qry)) $this->query($qry);
      if(empty($query_id)){
       $return = mysql_affected_rows($this->getresult());
      }else{
       $return = mysql_affected_rows($query_id);
      }
      return $return ? $return : $this->error();
    }
    //+======================================================+
    // returns the auto generated id from th
    //     e last insert action
    //+======================================================+
    public function getinsertid($connection_link = null){
    return mysql_insert_id(isset($connection_link) ? $connection_link : $this->connection);
    }
    //+======================================================+
    // close the connection to the mysql dat
    //     abase
    //+======================================================+
    public function close(){
    if(isset($this->connection)){
    return @mysql_close($this->connection);
    }
    else {
     return $this->error();
    }
    }
    //+======================================================+
    // outputs the mysql error
    //+======================================================+
    private function error(){
    if(mysql_error() != ''){
    echo '<b>mysql errorwww.111cn.net</b>: '.mysql_error().'<br/>';
    }
    }
    }

    //demo
    // database object initialization
$db = new mysql();
$db->connect("localhost", "root", "123456", "user");

// update query
//$db->query("update table_name set field_name = value where another_field = another_value");

// select with check for record amount

if ($db->hasresults("select * from userinfo")) {
//   loop through the user records, and get them as objects
//   note that the getobject method will use the last executed query when not provided with a new one
  while ($user = $db->getobject()) {
    echo "user $user->username is called $user->password<br /> ";
  }
}
else {
  echo "no results where found";
}

 代码如下 复制代码

class excel{

    /**
     *头的excel文件(前缀的行)
     *
     *从excel复制的xml规格。
     *
     * @访问私有
     * @无功串
     */
    var $header = "<?xml version="1.0" encoding="utf-8"?>
<workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
 xmlns:x="urn:schemas-microsoft-com:office:excel"
 xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
 xmlns:html="http://www.w3.org/tr/rec-html40">";

    /**
     *页脚的excel文件(附加到行)
     *
     *从excel复制的xml规格。
     *
     * @访问私有
     * @无功串
     */
    var $footer = "</workbook>";

    /**
     * document lines (rows in an array)
     *
     * @access private
     * @var array
     */
    var $lines = array ();

    /**
     工作表名称
     *
     *包含一个单一的工作表名称
     *
     * @访问私有
     * @无功串
     */
    var $worksheet_title = "table1";

    /**
  添加一个单行的文档字符串$
     *
     * @访问私有
     * @帕拉姆库马拉阵列一维阵列
     * @待办事项行创造应做减本-> addarray
     */
    function addrow ($array) {

        // initialize all cells for this row
        $cells = "";
       
        // foreach key -> write value into cells
        foreach ($array as $k => $v):
   
         // 加个字符串与数字的判断 避免生成的 excel 出现数字以字符串存储的警告
         if(is_numeric($v)) {
          // 防止首字母为 0 时生成 excel 后 0 丢失
          if(substr($v, 0, 1) == 0) {
           $cells .= "<cell><data ss:type="string">" . $v . "</data></cell> ";
          } else {
           $cells .= "<cell><data ss:type="number">" . $v . "</data></cell> ";
          }
         } else {
             $cells .= "<cell><data ss:type="string">" . $v . "</data></cell> ";
         }

        endforeach;

        // transform $cells content into one row
        $this->lines[] = "<row> " . $cells . "</row> ";

    }

    /**
    *添加一个数组到文档
     *
     *这应该是唯一的方法需要生成一个excel
     *文件。
     *
     * @访问公开
     * @帕拉姆库马拉数组二维数组
     * @待办事项可以转移到__construct()稍后
     */
    function addarray ($array) {

        // run through the array and add them into rows
        foreach ($array as $k => $v):
            $this->addrow ($v);
        endforeach;

    }

    /**
    设置工作表名称
     *
     *检查的字符串不允许字符(: /?*),
     *削减它的最大31个字符,并设置标题。该死
     *为何未允许字符无处可寻?视窗
     *帮助没有帮助...
     *
     * @访问公开
     * @帕拉姆库马拉字符串$标题设计标题
     */
    function setworksheettitle ($title) {

        // strip out special chars first
        $title = preg_replace ("/[\|:|/|?|*|[|]]/", "", $title);

        // now cut it to the allowed length
        $title = substr ($title, 0, 31);

        // set title
        $this->worksheet_title = $title;

    }

   /**
     *生成excel文件
     *
     *最后生成的excel文件,并使用header()函数
     *提供给浏览器。
     *
     * @访问公开
     * @帕拉姆库马拉字符串$文件名名称的excel文件来生成(... xls)中
     */
    function generatexml ($filename) {

        // deliver header (as recommended in php manual)
        header("content-type: application/vnd.ms-excel; charset=utf-8");
        header("content-disposition: inline; filename="" . $filename . ".xls"");

        // print out document to the browser
        // need to use strips教程lashes for the damn ">"
        echo stripslashes ($this->header);
        echo " <worksheet ss:name="" . $this->worksheet_title . ""> <table> ";
        echo "<column ss:index="1" ss:autofitwidth="0" ss:width="110"/> ";
        echo implode (" ", $this->lines);
        echo "</table> </worksheet> ";
        echo $this->footer;

    }

}

/**
 *  cakephp中使用方法
 *  注意 ** cakephp 配置文件 define('debug', 0);
 *
 *  vendor ('excel');
 *  $doc = array (
 *       0 => array ('中国', '中国人', '中国人民', '123456');
 *  );
 *  $xls = new excel;
 *  $xls->addarray ( $doc );
 *  $xls->generatexml ("mytest");
 */

/**
 *  非框架使用方法
 *
 *  require_once('excel.php');
 *  $doc = array (
 *       0 => array ('中国', '中国人', '中国人民', '123456');
 *  );
 *  $xls = new excel;
 *  $xls->addarray ( $doc );
 *  $xls->generatexml ("mytest");
 */

 代码如下 复制代码

$conn = new com("adodb.connection");
$connstr = "driver={microsoft access driver (*.mdb)}; dbq=". realpath("data/db.mdb");

$conn->open($connstr);
$rs = new com("adodb.recordset");
$rs->open("select * from szd_t",$conn,1,1);
while(! $rs->eof)
$f = $rs->fields(1);
echo $f->value;
$rs->movenext();

在WEB开发中php连接mysql数据库是肯定会用到的,如果你不会连接数据库就等不会WEB,我们提供这一款连接mysql数据库的类文件,可以方便快捷使php与mysql建立连接。

/*

 代码如下 复制代码

 * created on 2010-4-21
 *
 * the class for control mysql
 *
 * made by s71ence
 *
 * @$host
 * @$user_name
 * @$user_pwd
 * @$data_base
 * @$coding
 */
 class mysql
 {
 private $host;//主机名
 private $user_name;//用户名
 private $user_pwd;//密码
 private $data_base;//数据库名
 private $coding;//编码

//构造函数 进行初始化操作
 function __construct($host,$user_name,$user_pwd,$data_base,$coding)
 {
  $this->host=$host;
  $this->user_name=$user_name;
  $this->user_pwd=$user_pwd;
  $this->data_base=$data_base;
  $this->coding=$coding;
  $this->connect();//初始化连接
 }

/*********************************************************************************************
 * 数据库
 * 基本方法
 ********************************************************************************************/

//数据库连接
 function connect()
 {
  $link=mysql_connect($this->host,$this->user_name,$this->user_pwd) or die($this->error());
  mysql_select_db($this->data_base,$link) or die("无法连接数据库".$this->data_base);
  mysql_query("set names '$this->coding'");
 }

//错误信息
 function error()
 {
  return mysql_error();
 }

//mysql_query()方法
 function query($sql, $type = '')
 {
     if(!($query = mysql_query($sql)))
  {
   $this->show('say:', $sql);
  }

  //echo $sql."<br/>";//测试完成后 注释
     return $query;
 }

//sql语句显示
 function show($message = '', $sql = '')
 {
  if(!$sql)
  {
   echo $message;
  }
  else
  {
   echo $message.'<br>'.$sql;
  }
 }

//mysql_affected_rows()方法
    function affected_rows()
 {
  return mysql_affected_rows();
 }

//mysql_result方法
 function result($query, $row)
 {
  return mysql_result($query, $row);
 }

//mysql_num_rows方法
 function num_rows($query)
 {
  return @mysql_num_rows($query);
 }

//mysql_num_fields方法
 function num_fields($query)
 {
  return mysql_num_fields($query);
 }

//mysql_free_result方法
 function free_result($query)
 {
  return mysql_free_result($query);
 }

//mysql_insert_id方法
 function insert_id()
 {
  return mysql_insert_id();
 }

//mysql_fetch_row方法
 function fetch_row($query)
 {
  return mysql_fetch_row($query);
 }

//mysql_get_server_info方法
 function version()
 {
  return mysql_get_server_info();
 }

//mysql_fetch_array()方法
 function fetch_array($result)
 {
  return mysql_fetch_array($result);
 }

//mysql_close方法
 function close()
 {
  return mysql_close();
 }


/*********************************************************************
 * 数据库
 * 功能方法
 *********************************************************************/

/*
 * insert方法
 *  $table 表名
 * $fields 字段名
 * $value 字段值
 */

 function fn_insert($table,$fields,$values)
 {
  return $this->query("insert into $table ($fields) values ($values)");
  $this->close();
 }


/*
 * select方法
 *  $table 表名
 * $fields 字段名
 * $condition 查询条件
 * $order 排序条件
 * $limit 取出条数
 */
 function fn_select($table,$fields,$condition,$order,$limit)
 {
  $query="select $fields from $table";

  if($condition!="")
  {
   $query.=" where $condition";
  }

  if($order!="")
  {
   $query.=" order by $order ";
  }

  if($limit!="")
  {
   $query.=" limit $limit";
  }

  return $this->query($query);
  $this->close();
 }


/*
 * delete方法
 * $table 表名
 * $fields 字段名
 * $values 字段值
 */
 function fn_delete($table,$condition)
 {
  return $this->query("delete from $table where $condition");
  $this->close();
 }


/*
 * update方法
 * $table 表名
 * $fields 字段名
 * $values 字段值
 */
 function fn_update($table,$set,$condition)
 {
  $sql="update $table set $set";
  if($condition!="")
  {
   $sql.=" where $condition";
  }

  return $this->query($sql);
  $this->close();
 }


/*
 * 析构函数,垃圾回收
 */
 function __destruct()
 {
  //echo "clear";
    }
 }
 


 //调用方法

 代码如下 复制代码

 $db =  new mysql('127.0.0.1','username','password','databasename',"utf8");

[!--infotagslink--]

相关文章

  • PHP 数据库缓存Memcache操作类

    操作类就是把一些常用的一系列的数据库或相关操作写在一个类中,这样调用时我们只要调用类文件,如果要执行相关操作就直接调用类文件中的方法函数就可以实现了,下面整理了...2016-11-25
  • C#连接SQL数据库和查询数据功能的操作技巧

    本文给大家分享C#连接SQL数据库和查询数据功能的操作技巧,本文通过图文并茂的形式给大家介绍的非常详细,需要的朋友参考下吧...2021-05-17
  • C#从数据库读取图片并保存的两种方法

    这篇文章主要介绍了C#从数据库读取图片并保存的方法,帮助大家更好的理解和使用c#,感兴趣的朋友可以了解下...2021-01-16
  • Intellij IDEA连接Navicat数据库的方法

    这篇文章主要介绍了Intellij IDEA连接Navicat数据库的方法,本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借价值,需要的朋友可以参考下...2021-03-25
  • 在数据库里将毫秒转换成date格式的方法

    在开发过程中,我们经常会将日期时间的毫秒数存放到数据库,但是它对应的时间看起来就十分不方便,我们可以使用一些函数将毫秒转换成date格式。 一、 在MySQL中,有内置的函数from_unixtime()来做相应的转换,使用如下: 复制...2014-05-31
  • C#操作本地文件及保存文件到数据库的基本方法总结

    C#使用System.IO中的文件操作方法在Windows系统中处理本地文件相当顺手,这里我们还总结了在Oracle中保存文件的方法,嗯,接下来就来看看整理的C#操作本地文件及保存文件到数据库的基本方法总结...2020-06-25
  • 如何解决局域网内mysql数据库连接慢

    通过内网连另外一台机器的mysql服务, 确发现速度N慢! 等了大约几十秒才等到提示输入密码。 但是ping mysql所在服务器却很快! 想到很久之前有过类似的经验, telnet等一些服务在连接请求的时候,会做一些反向域名解析(如果...2015-10-21
  • MySQL快速复制数据库数据表的方法

    某些时候,例如为了搭建一个测试环境,或者克隆一个网站,需要复制一个已存在的mysql数据库。使用以下方法,可以非常简单地实现。假设已经存在的数据库名字叫db1,想要复制一份,命名为newdb。步骤如下:1. 首先创建新的数据库newd...2015-10-21
  • mysqldump命令导入导出数据库方法与实例汇总

    mysqldump命令的用法1、导出所有库系统命令行mysqldump -uusername -ppassword --all-databases > all.sql 2、导入所有库mysql命令行mysql>source all.sql; 3、导出某些库系统命令行mysqldump -uusername -ppassword...2015-10-21
  • Mysql数据库错误代码中文详细说明

    1005:创建表失败1006:创建数据库失败1007:数据库已存在,创建数据库失败1008:数据库不存在,删除数据库失败1009:不能删除数据库文件导致删除数据库失败1010:不能删除数据目录导致删除数据库失败1011:删除数据库...2013-09-23
  • c#异步读取数据库与异步更新ui的代码实现

    这篇文章主要介绍了c#从数据库里取得数据并异步更新ui的方法,大家参考使用吧...2020-06-25
  • Yii2.0高级框架数据库增删改查的一些操作

    yii2.0框架是PHP开发的一个比较高效率的框架,集合了作者的大量心血,下面通过用户为例给大家详解yii2使用中的一些基本的增删改查操作。 User::find()->all(); //返回所有用户数据; User::findOne($id); //返回 主键...2015-11-24
  • MYSQL数据库使用UTF-8中文编码乱码的解决办法

    1.用phpmyadmin创建数据库和数据表 创建数据库的时候,请将“整理”设置为:“utf8_general_ci” 或执行语句: 复制代码 代码如下:CREATE DATABASE `dbname` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci; 创...2015-10-21
  • springBoot 项目排除数据库启动方式

    这篇文章主要介绍了springBoot 项目排除数据库启动方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-09-10
  • 详解在IDEA中将Echarts引入web两种方式(使用js文件和maven的依赖导入)

    这篇文章主要介绍了在IDEA中将Echarts引入web两种方式(使用js文件和maven的依赖导入),本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2020-07-11
  • Linux 下使用shell脚本定时维护数据库的案例

    这篇文章主要介绍了Linux 下使用shell脚本定时维护数据库,本文通过案例分析给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2020-07-11
  • PHP连接公司内部服务器的MYSQL数据库的简单实例

    “主机,用户名,密码”得到连接、“数据库,sql,连接”得到结果,最后是结果的处理显示。当然,数据库连接是扩展库为我们完成的,我们能做的仅仅是处理结果而已。...2013-09-29
  • C#连接加密的Sqlite数据库的方法

    对数据加密分两种,一种是对数据库本身进行加密,另一种是对数据表中的数据进行加密,下面通过本文给大家介绍C#连接加密的Sqlite数据库的方法,感兴趣的朋友一起看看吧...2020-06-25
  • Java连接数据库oracle中文乱码解决方案

    这篇文章主要介绍了Java连接数据库oracle中文乱码解决方案,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下...2020-05-16
  • 深入分析C#连接Oracle数据库的连接字符串详解

    本篇文章是对C#连接Oracle数据库的连接字符串进行了详细的分析介绍,需要的朋友参考下...2020-06-25