我使用以下代码但显示解析错误,所以有人请提供相应的解决方案吗?
/****** Include the EXCEL Reader Factory ***********/
set_include_path(get_include_path() . PATH_SEPARATOR . 'Classes/');
include 'excel.php';
if(isset($_POST) && !empty($_FILES['excelupload']['name'])) {
//print_r($_FILES['excelupload']);
$namearr = explode(".",$_FILES['excelupload']['name']);
if(end($namearr) != 'xls' && end($namearr) != 'xlsx') {
echo '<p> Invalid File </p>';
$invalid = 1;
}
if($invalid != 1) {
$response = move_uploaded_file($_FILES['excelupload']['tmp_name'],$_FILES['excelupload']['name']); // Upload the file to the current folder
if($response) {
try {
$objPHPExcel = PHPExcel_IOFactory::load($_FILES['excelupload']['name']);
} catch(Exception $e) {
die('Error : Unable to load the file : "'.pathinfo($_FILES['excelupload']['name'],PATHINFO_BASENAME).'": '.$e->getMessage());
}
$allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
$arrayCount = count($allDataInSheet); // Total Number of rows in the uploaded EXCEL file
$string = "insert into ".tablename." (name,city,designation) VALUES('".$name."','".$city."','".$designation."')";
for($i=2;$i<=$arrayCount;$i++) {
$name = trim($allDataInSheet[$i]["A"]);
$city = trim($allDataInSheet[$i]["B"]);
$designation = trim($allDataInSheet[$i]["B"]);
$string .= "('".$name."','".$city."','".$designation."')";
}
$string = substr($string,0,-1);
mysql_query($string); // Insert all the data into one query
}
}// End Invalid Condition
}
答案 0 :(得分:0)
一个很大的问题是你正在创建一个MySQL语句作为字符串
$string = "insert into ".tablename." (name,city,designation) VALUES('".$name."','".$city."','".$designation."')";
在变量定义之前使用变量$name
,$city
和$designation
,然后在循环中扩展该字符串。
这会创建一个类似于:
的字符串insert into myTable (name,city,designation) VALUES ('','','')('A','B','C')('D','E','F')
这不是有效的SQL
切换到使用带有预准备语句和占位符的MySQLi或PDO,然后将变量绑定到占位符并在循环中执行查询。
准备好的声明和占位符不适用于旧的已弃用的MySQL界面(无论如何你不应该使用这些天,因为它已经过时并且已弃用)。
我建议切换到MySQLi或PDO,然后阅读prepared statements
修改强>
以下是使用MySQLi执行此操作的代码的基础....您必须自己创建自己的数据库连接和任何错误处理
$query = "insert into " . tablename . " (name,city,designation) VALUES(?, ?, ?)";
$statement = $mysqli->prepare($query);
for ($i = 2; $i <= $arrayCount; $i++) {
$name = trim($allDataInSheet[$i]["A"]);
$city = trim($allDataInSheet[$i]["B"]);
$designation = trim($allDataInSheet[$i]["B"]);
$statement->bind_param('sss', $name, $city, $designation);
$statement->execute();
}
阅读PHP文档并了解其工作原理