search
HomeBackend DevelopmentPHP TutorialPHP上传Excel并批量添加数据到pgsql的问题,期待高人解答!

下面这个代码的作用是上传Excel并读取其中的数据,批量添加数据到pgsql数据库中,目前已成功实现上传并将数据读出来,但是在批量插入数据时出现错误(无法执行SQL语句),但用输出的$sql的值的语句直接在pgAdminIII中运行,又是成功的。哪位大神帮助看一下,不胜感激!

<?phpinclude_once("reader.php");include_once("conn.php");$remotefilename= date("Ymdhis").".xls";if (substr($_FILES["file"]["name"],-4)==".xls"){  if ($_FILES["file"]["error"] > 0)    {    echo "Return Code: " . $_FILES["file"]["error"] . "<br />";    }  else    {     if(move_uploaded_file($_FILES["file"]["tmp_name"],"xlstmp/" .$remotefilename)==1)	 {	    //上传成功并开始读取xls文件		$data = new Spreadsheet_Excel_Reader();        $data->setOutputEncoding('CP936');		$data->read("xlstmp/" .$remotefilename);		$count=0;		if($data->sheets[0]['numRows']>=2 && $data->sheets[0]['numCols']>=2)		{			for ($i = 2; $i <= $data->sheets[0]['numRows']; $i++)			{			$s="";			for ($j = 1; $j <= $data->sheets[0]['numCols']; $j++)				{				if(strlen($data->sheets[0]['cells'][$i][$j])==0) break;				$s.= $data->sheets[0]['cells'][$i][$j]."|";				}			 if(strlen($s)!=0)				{				 $count++;				$ss =explode('|',$s);//将关键词以空格分割到数组中。								// $sql="INSERT INTO zikao_tzd_kecheng(\"KC_DM\",\"KC_MC\")  VALUES('1111','ok')";//执行上面这句都是可以的				 $sql="INSERT INTO zikao_tzd_kecheng(\"KC_DM\",\"KC_MC\")  VALUES('".$ss[0]."','".$ss[1]."')";//执行上面这句就不成功。				// $sql="INSERT INTO zikao_tzd_kecheng(\"KC_DM\",\"KC_MC\")  VALUES('".$data->sheets[0]['cells'][$i][1]."','".$data->sheets[0]['cells'][$i][2]."')";				 				 echo $sql."<br>";                 $result = $PG -> query($sql);				 				 }			}			echo $count."records";		}		else		 {			echo "xls's rows or columns is so few.";		 }	}	 else         echo "upload failed.";    } }else  {  echo "invalid file";  }   $PG ->close();?>


回复讨论(解决方案)

再加30分,期待高人解答!

没有错误信息吗

错误提示就是:The database query fail
可我直接用调试时输出的$sql的值直接在pgAdminIII中执行,又是成功插入数据的。
如:INSERT INTO zikao_tzd_kecheng("KC_DM","KC_MC") VALUES('3708','中国近现代史纲要')
但VALUES中使用从Excel可读出来的变量又不行。

// $sql="INSERT INTO zikao_tzd_kecheng(\"KC_DM\",\"KC_MC\")  VALUES('1111','ok')";
//执行上面这句都是可以成功插入的
$sql="INSERT INTO zikao_tzd_kecheng(\"KC_DM\",\"KC_MC\")  VALUES('".$ss[0]."','".$ss[1]."')";
//但上面这句用变量$ss[0],$ss[1]就插入不成功,提示The database query fail

echo pg_last_error($PG);   看看

echo $sql; 
贴出结果看看

这是echo $sql的结果。
INSERT INTO zikao_tzd_kecheng("KC_DM","KC_MC") VALUES('6029','工作分析')
The database query fail.INSERT INTO zikao_tzd_kecheng("KC_DM","KC_MC") VALUES('3708','中国近现代史纲要')
The database query fail.INSERT INTO zikao_tzd_kecheng("KC_DM","KC_MC") VALUES('0112','计算机基础')
The database query fail.INSERT INTO zikao_tzd_kecheng("KC_DM","KC_MC") VALUES('0003','测试课程3')
The database query fail.INSERT INTO zikao_tzd_kecheng("KC_DM","KC_MC") VALUES('0003','测试课程4')
The database query fail.INSERT INTO zikao_tzd_kecheng("KC_DM","KC_MC") VALUES('0003','测试课程5')
The database query fail.INSERT INTO zikao_tzd_kecheng("KC_DM","KC_MC") VALUES('0003','测试课程6')
The database query fail.INSERT INTO zikao_tzd_kecheng("KC_DM","KC_MC") VALUES('0003','测试课程7')
The database query fail.INSERT INTO zikao_tzd_kecheng("KC_DM","KC_MC") VALUES('0003','测试课程8')
The database query fail.INSERT INTO zikao_tzd_kecheng("KC_DM","KC_MC") VALUES('0003','测试课程9')
The database query fail.INSERT INTO zikao_tzd_kecheng("KC_DM","KC_MC") VALUES('0003','测试课程10')
The database query fail.INSERT INTO zikao_tzd_kecheng("KC_DM","KC_MC") VALUES('0003','测试课程11')
The database query fail.INSERT INTO zikao_tzd_kecheng("KC_DM","KC_MC") VALUES('0003','测试课程12')
The database query fail.INSERT INTO zikao_tzd_kecheng("KC_DM","KC_MC") VALUES('0003','测试课程13')
The database query fail.INSERT INTO zikao_tzd_kecheng("KC_DM","KC_MC") VALUES('0003','测试课程14')
The database query fail.INSERT INTO zikao_tzd_kecheng("KC_DM","KC_MC") VALUES('0003','测试课程15')
The database query fail.INSERT INTO zikao_tzd_kecheng("KC_DM","KC_MC") VALUES('0003','测试课程16')
The database query fail.INSERT INTO zikao_tzd_kecheng("KC_DM","KC_MC") VALUES('0003','测试课程17')
The database query fail.INSERT INTO zikao_tzd_kecheng("KC_DM","KC_MC") VALUES('0003','测试课程18')
The database query fail.INSERT INTO zikao_tzd_kecheng("KC_DM","KC_MC") VALUES('0003','测试课程19')
The database query fail.INSERT INTO zikao_tzd_kecheng("KC_DM","KC_MC") VALUES('0003','测试课程20')
The database query fail.INSERT INTO zikao_tzd_kecheng("KC_DM","KC_MC") VALUES('0003','测试课程21')
The database query fail.INSERT INTO zikao_tzd_kecheng("KC_DM","KC_MC") VALUES('0003','测试课程22')
The database query fail.INSERT INTO zikao_tzd_kecheng("KC_DM","KC_MC") VALUES('0003','测试课程23')
The database query fail.INSERT INTO zikao_tzd_kecheng("KC_DM","KC_MC") VALUES('0003','测试课程24')
The database query fail.INSERT INTO zikao_tzd_kecheng("KC_DM","KC_MC") VALUES('0003','测试课程25')
The database query fail.

conn.php内容

<?phpinclude 'class/PGDB.php';  $PG = new pgsql("localhost", "5432", "name", "user", "pass");  $PG->connect();if(!$PG)  {  echo "无法连接到PostGreSQL数据库!";exit;} ?>

PGDB.php内容
<?php  class pgsql {  private $linkid; // PostgreSQL连接标识符  private $host; // PostgreSQL服务器主机  private $port; // PostgreSQL服务器主机端口  private $user; // PostgreSQL用户  private $passwd; // PostgreSQL密码  private $db; // Postgresql数据库  private $result; // 查询的结果  private $querycount; // 已执行的查询总数  /* 类构造函数,用来初始化$host、$user、$passwd和$db字段。 */  function __construct($host, $port ,$db, $user, $passwd) {  $this->host = $host;  $this->port = $port;  $this->user = $user;  $this->passwd = $passwd;  $this->db = $db;  }  /* 连接Postgresql数据库 */  function connect(){  try{  $this->linkid = @pg_connect("host=$this->host port=$this->port dbname=$this->db  user=$this->user password=$this->passwd");  if (! $this->linkid)  throw new Exception("Could not connect to PostgreSQL server.");  }  catch (Exception $e) {  die($e->getMessage());  }  }  /* 执行数据库查询。 */  function query($query){  try{  $this->result = @pg_query($this->linkid,$query);  if(! $this->result)  throw new Exception("The database query fail.");  }  catch (Exception $e){  echo $e->getMessage();  }  $this->querycount++;  return $this->result;  }  /* 确定受查询所影响的行的总计。 */  function affectedRows(){  $count = @pg_affected_rows($this->linkid);  return $count;  }  /* 确定查询返回的行的总计。 */  function numRows(){  $count = @pg_num_rows($this->result);  return $count;  }  /* 将查询的结果行作为一个对象返回。 */  function fetchObject(){  $row = @pg_fetch_object($this->result);  return $row;  }  /* 将查询的结果行作为一个索引数组返回。 */  function fetchRow(){  $row = @pg_fetch_row($this->result);  return $row;  }  /* 将查询的结果行作为一个关联数组返回。 */  function fetchArray(){  $row = @pg_fetch_array($this->result);  return $row;  }  /* 返回在这个对象的生存期内执行的查询总数。这不是必须的,但是您也许会感兴趣。 */  function numQueries(){  return $this->querycount;  }  function close()	 {	 @pg_close($this->linkid);	 }}  ?>  

你这个应该是页面编码的问题。中文可能乱码了。
mysql_query('set names utf8')

的确如lang11zi 所说,我把需要写入的字符串转化为 utf8就ok了。因为字符串是从 Excel读出来的,默认是GB2312。
谢谢以上各位的解答。散分。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)