我尝试从excel(.xls)中提取数据(中文字符),但插入时,数据库无法识别字符(显示为空白和符号)。请帮我解决问题。
<html>
<body>
<form action="upload_file_xls.php" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file" /><br/>
<input type="submit" name="insert" value="Upload"/>
</form>
</body>
<?php
if(isset($_POST['insert'])){
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] ;
}
else{
include 'excel/reader.php';
$excel = new Spreadsheet_Excel_Reader();
$file = $_FILES['file']['tmp_name'];
$excel->read($file);
$x=1;
while($x<=$excel->sheets[0]['numRows']) {
$number = isset($excel->sheets[0]['cells'][$x][1]) ? $excel->sheets[0]['cells'][$x][1] : '';
$province = isset($excel->sheets[0]['cells'][$x][2]) ? $excel->sheets[0]['cells'][$x][2] : '';
$city = isset($excel->sheets[0]['cells'][$x][3]) ? $excel->sheets[0]['cells'][$x][3] : '';
$alphabet = isset($excel->sheets[0]['cells'][$x][4]) ? $excel->sheets[0]['cells'][$x][4] : '';
$link = mysql_connect('localhost', 'root', '');
mysql_set_charset('utf8',$link);
$db_selected = mysql_select_db('sugoroku01', $link);
if (!$db_selected) { die ('Database access error : ' . mysql_error());}
$query = "INSERT INTO `province_city_tbl`(`province`, `city`, `alphabet`)
VALUES ('".$province."', '".$city."', '".$alphabet."') ";
mysql_query($query) or die('Error, Feedback insert into database failed');
$x++;
}
}
}
?>
</html>
答案 0 :(得分:0)
在插入内容之前尝试运行查询"SET NAMES utf8"
。
mysql_query("SET NAMES utf8");
此外,您无需将mysql_connect()
置于循环中。
试试这段代码:
<html>
<body>
<form action="upload_file_xls.php" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file" /><br/>
<input type="submit" name="insert" value="Upload"/>
</form>
</body>
<?php
$link = mysql_connect('localhost', 'root', '');
$db_selected = mysql_select_db('sugoroku01', $link);
if (!$db_selected) { die ('Database access error : ' . mysql_error()); }
mysql_query("SET NAMES utf8");
mysql_query("SET CHARACTER SET utf8");
if(isset($_POST['insert'])){
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] ;
}
else{
include 'excel/reader.php';
$excel = new Spreadsheet_Excel_Reader();
$file = $_FILES['file']['tmp_name'];
$excel->read($file);
$x=1;
while($x<=$excel->sheets[0]['numRows']) {
$number = isset($excel->sheets[0]['cells'][$x][1]) ? $excel->sheets[0]['cells'][$x][1] : '';
$province = isset($excel->sheets[0]['cells'][$x][2]) ? $excel->sheets[0]['cells'][$x][2] : '';
$city = isset($excel->sheets[0]['cells'][$x][3]) ? $excel->sheets[0]['cells'][$x][3] : '';
$alphabet = isset($excel->sheets[0]['cells'][$x][4]) ? $excel->sheets[0]['cells'][$x][4] : '';
$query = "INSERT INTO `province_city_tbl`(`province`, `city`, `alphabet`)
VALUES ('".$province."', '".$city."', '".$alphabet."') ";
mysql_query($query) or die('Error, Feedback insert into database failed');
$x++;
}
}
}
?>
</html>