gpt4 book ai didi

php - 使用 PDO 使用 PHP 导入 .CSV 文件

转载 作者:行者123 更新时间:2023-12-02 04:53:53 25 4
gpt4 key购买 nike

我在将 .CSV 数据导入 SQL 数据库时遇到问题。我试图在我的 PHP 文件中使用 PDO 来完成此操作,但我似乎无法弄清楚。

if (isset($_FILES['uploadedfile'])) {   

// get the csv file and open it up
$file = $_FILES['uploadedfile']['tmp_name'];
$handle = fopen($file, "r");
try {
// prepare for insertion
$query_ip = $db->prepare('
INSERT INTO projects (
id, project_name, contact, pm, apm,
est_start, est_end, trips, tasks, perc_complete,
bcwp, actual, cpi, bcws, bac,
comments, status, project_revenue, profit_margin, pm_perc,
audited, account_id
) VALUES (
?, ?, ?, ?, ?,
?, ?, ?, ?, ?,
?, ?, ?, ?, ?,
?, ?, ?, ?, ?,
?, ?
)');
$data = fgetcsv($handle,1000,",","'");
$query_ip->execute($data);
$count = $query_ip->rowCount();
fclose($handle);

} catch(PDOException $e) {
die($e->getMessage());
}

echo 'Projects imported ' . $count . ' rows were affected';

} else {
echo 'Could not import projects';
}

现在这可行了,有点。它导入数据,但您可能已经猜到,这只是插入 .CSV 文件的第一行,顺便说一下,这是列标题。所以我需要跳过第一行并循环浏览此 .CSV 文件的其余部分。

显然,给我一些代码可以解决这个问题,但除此之外,我还想解释一下如何使用 PHP 数据对象 (PDO) 正确地执行此操作。我遇到的所有示例要么存在巨大缺陷,要么不使用 PDO。欢迎和感谢任何帮助。

最佳答案

这些评论帮助我得出了这个答案。我使用了以下代码

if (isset($_FILES['uploadedfile'])) {   

// get the csv file and open it up
$file = $_FILES['uploadedfile']['tmp_name'];
$handle = fopen($file, "r");
try {
// prepare for insertion
$query_ip = $db->prepare('
INSERT INTO projects (
id, project_name, contact, pm, apm,
est_start, est_end, trips, tasks, perc_complete,
bcwp, actual, cpi, bcws, bac,
comments, status, project_revenue, profit_margin, pm_perc,
audited
) VALUES (
?, ?, ?, ?, ?,
?, ?, ?, ?, ?,
?, ?, ?, ?, ?,
?, ?, ?, ?, ?,
?
)
');

// unset the first line like this
fgets($handle);

// created loop here
while (($data = fgetcsv($handle, 1000, ',')) !== FALSE) {
$query_ip->execute($data);
}

fclose($handle);

} catch(PDOException $e) {
die($e->getMessage());
}

echo 'Projects imported';

} else {
echo 'Could not import projects';
}

我希望这有助于 future 的读者使用 PDO 正确导入他们的 .CSV 文件。应该注意的是,这应该在实时服务器/站点上使用。此代码对潜在有害上传的保护为 0。

关于php - 使用 PDO 使用 PHP 导入 .CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18342730/

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