简体   繁体   English

导入 LOAD DATA INFILE 时将我的 php 变量连接到 csv 数据

[英]Concatenate my php variable to csv data when importing LOAD DATA INFILE

I need to import some csv files to mysql.我需要将一些 csv 文件导入 mysql。

I recently found about the LOAD DATA INFILE, I checked the manual, as far as I understand, to imports each line of.csv file to the database.我最近发现有关 LOAD DATA INFILE 的信息,据我了解,我查看了手册,将每一行 .csv 文件导入到数据库中。

I was wondering if there's an option to concatenate an extra value to what the csv file contains.我想知道是否有一个选项可以将额外的值连接到 csv 文件包含的内容。

For example: my table has 3 columns.例如:我的表有 3 列。

MYTABLE(#name,#email,company_adrs); MYTABLE(#name,#email,company_adrs);

The csv file has data for "name,email" only, and I have the address in a php variable. csv 文件只有“姓名、电子邮件”的数据,我在 php 变量中有地址。

With a normal loop, I would achieve this as follows:使用正常循环,我将按如下方式实现:

//open file
while (/* not end of file, read eachline*/)
{
  $current_line_of_csv_file; // contains: "John,john@john.com" without the 3rd column
  $myAddrsVar= mysqli_real_escape_string($db, $_POST['adrs']); //"44 company st" 
  $insert = $db->query("INSERT MYTABLE (name,email,company_adrs) VALUES ( $current_line_of_csv_file,'".$myAddrsVar."')");

}

With this method I have to loop through each line the csv and do a query in each iteration.使用这种方法,我必须遍历 csv 的每一行并在每次迭代中进行查询。

I was wondering if LOAD DATA INFILE has a method to concatenate my data to the csv file?我想知道 LOAD DATA INFILE 是否有一种方法可以将我的数据连接到 csv 文件? if so, how can I achieve it?如果是这样,我该如何实现?

Thanks in advance提前致谢

Given your situation, I would recommend using PHP all-in-all and insert data into MySQL that way.鉴于您的情况,我建议使用 PHP all-in-all 并以这种方式将数据插入 MySQL。

https://www.php.net/manual/en/function.str-getcsv.php can help you parse CSV into an array. https://www.php.net/manual/en/function.str-getcsv.php可以帮助您将 CSV 解析为数组。 Add to the array the address.将地址添加到数组中。 Now, you'd have the dataset in an array.现在,您将在数组中拥有数据集。

Use prepared statements like shown here https://websitebeaver.com/prepared-statements-in-php-mysqli-to-prevent-sql-injection and insert data one after the other.使用此处所示的准备好的语句https://websitebeaver.com/prepared-statements-in-php-mysqli-to-prevent-sql-injection并一个接一个地插入数据。

Use transactions so that all data is inserted or no data is insert.使用事务以便插入所有数据或不插入任何数据。 See How to start and end transaction in mysqli?请参阅如何在 mysqli 中启动和结束事务? . .

I'd avoid using LOAD DATA INLINE because the volume of data is not that big.我会避免使用 LOAD DATA INLINE 因为数据量不是那么大。 If you really want to use it and add another column, you can use SET statement.如果你真的想使用它并添加另一列,你可以使用SET语句。 There's an example of that here: Add extra column of data when using LOAD DATA LOCAL INFILE这里有一个例子: Add extra column of data when using LOAD DATA LOCAL INFILE

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM