gpt4 book ai didi

php - 使用php将csv文件导入数据库

转载 作者:行者123 更新时间:2023-11-29 21:21:54 24 4
gpt4 key购买 nike

我创建了以下 php 代码,将 .csv 文件导入到 phpmyadmin 上运行的 mysql 数据库中。代码如下:

<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
$db_host = 'localhost';
$db_user = 'root';
$db_pwd = '';

$database = 'mydatabase';
$table = 'demo';

if (!@mysql_connect($db_host, $db_user, $db_pwd))
die("Can't connect to database");

if (!mysql_select_db($database))
die("Can't select database");


if(isset($_POST['submit']))
{
$fname = $_FILES['sel_file']['name'];
echo 'upload file name: '.$fname.' ';
$chk_ext = explode(".",$fname);

if(strtolower(end($chk_ext)) == "csv")
{

$filename = $_FILES['sel_file']['tmp_name'];
$handle = fopen($filename, "r");

while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
$sql = "INSERT into demo(orders,quantity,country,dates,comment) values('$data[0]','$data[1]','$data[2]', '$data[3]','$data[4]')";
mysql_query($sql) or die(mysql_error());
}

fclose($handle);
echo "Successfully Imported";

}
else
{
echo "Invalid File";
}
}

?>
<h1>Import CSV file</h1>
<form action='<?php echo $_SERVER["PHP_SELF"];?>' method='post' enctype="multipart/form-data">
Import File : <input type='file' name='sel_file' size='20'>
<input type='submit' name='submit' value='submit'>
</form>

提交 .csv 文件后,它会显示消息“导入成功”,但是当我检查数据库时,仅 .csv 文件中的第一行被导入到数据库中。其他记录则不然。

最佳答案

不要使用mysql_,将其更改为PDO或mysqli。话虽这么说,我已经更改了您的代码以分解每一行,然后将值分配给列表。这对我有用。

if(isset($_POST['submit']))
{
$fname = $_FILES['sel_file']['name'];
echo 'upload file name: '.$fname.' ';

$chk_ext = explode(".",$fname);

if(strtolower(end($chk_ext)) == "csv")
{
foreach (file($fname) as $row)
{
list($data0, $data1, $data2, $data3, $data4) = explode(",", $row);
$sql = "INSERT into demo(orders,quantity,country,dates,comment) values('$data0','$data1','$data2', '$data3','$data4')";
mysql_query($sql) or die(mysql_error());
}

echo "Successfully Imported";
}
else
{
echo "Invalid File";
}
}

关于php - 使用php将csv文件导入数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35684503/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com