php - 将 csv 文件中的值插入到 MySQL 表中

标签 php mysql csv

我正在尝试将从 csv 文件中提取的值插入到 mysql 表中。它运行但表未填充。我已尝试调试最后一个 XXXX,但看不到我的错误。回显这些值给我正确的 SQL,但是当涉及到 INSERT 时 - 没有骰子。

非常感谢您的帮助。

<?php 

$host = 'localhost';
$user = 'fulltime_admin';
$pass = 'secret';
$database = 'fulltime_db';

$db = mysql_connect($host, $user, $pass);
mysql_query($database, $db);

//////////////////////////////// EDIT //////////////////////////////////// 

$redirect_num = 500;   // Select how many rows to insert each time before refresh. 
// More rows = faster insertion. However cannot be too high otherwise it will timeout. 

$filename = "ps4_emails.csv"; // The file we are going to get the data from... 

$table = "`ps4_emails`"; 

////////////////////////////// END EDIT ////////////////////////////////// 

$file = file($filename); 
$lines = count($file); 

// Have we just redirected? 
$nextline = $_GET['nextline']; 
if (!isset($nextline)){ 
    $nextline = 0; 
} 

$query = "INSERT INTO ".$table." (email) VALUES ('".$final_line[0]."')";

for ($line=$nextline; $line<=$lines; $line++){ 

    $final_line = explode(",", $file[$line]); 

    if ($line!=$lines){ 
        mysql_query($query,$db); 

    } 

    if ($line % $redirect_num){ 

        // something needs to go here
    } else { 
        $nextline = $line+1; 
        exit ('<meta http-equiv="refresh" content="0;url=texttomysqlemails.php?nextline='.$nextline.'" />'); 
    } 

    echo  ( $line==$lines ) ? "Done" : ""; 

} 
?>

最佳答案

将您的查询放入循环中,以便将其与变量 $final_line 一起使用。

试试这个:

$final_line = explode(",", $file[$line]); 

if ($line!=$lines){ 
   $query = "INSERT INTO ".$table." (email) VALUES ('".$final_line[0]."')";
    mysql_query($query,$db); 
} 

不要使用mysql_*。它已被弃用并从 PHP 7 中删除。使用 mysqli_*PDO

关于php - 将 csv 文件中的值插入到 MySQL 表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35505885/

相关文章:

php - PSR-2 数组和方法链接的编码标准?

mysql - 关于从 SQL Server 更改为 MySql 的建议

php - 更改来自数据库的日期格式?

mysql - 如何根据 mysql 中的实际行号生成重复行的唯一编号

php - 随机播放并显示 .txt 文件的内容

PHP 服务器输出关于 FD_SETSIZE 的警告

php - 调用非对象上的成员函数count()(Laravel 5)

linq - 使用 C# .Net 4.0 LINQ 嵌入逗号的 CSV

csv - BizTalk 平面文件架构 - 即使收到空白平面文件也生成 XML 文件

python - 文件 python 的压缩列表