gpt4 book ai didi

php - 如何使用 php 加载 txt 文件并循环内容以查询数据库

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

我有一段代码无法正常工作。我正在尝试循环遍历一个大约 1k 行的 txt 文件,每行都有一个文件名。然后将每个文件名循环到 mysql 查询中,如果该文件名匹配,则从表中删除一行。

<?php 
$handle = fopen("corrupt.txt", "r");
$link = mysqli_connect("localhost", "user", "pass", "listings");

if ($handle) {
while (($line = fgets($handle)) !== false) {
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "DELETE FROM images WHERE images_file_name like $line";
if(mysqli_query($link, $sql)){
}
else{
echo "ERROR: Could not able to execute $sql. "
. mysqli_error($link);
}
mysqli_close($link);
}
} else {

}
fclose($handle);
?>

最佳答案

第一:始终避免在循环内进行 mysql 查询。

// get data as an array
$file = file('data.txt');

// check if datasource has at least one line
if(count($file) > 0){

// create delete-array
$delete = array();

// loop trough each array element
foreach($file as $line){
// trim current line
$line = trim($line);
// check if line is not empty
if(!empty($line)){
// add line to delete-array
$delete[] = $line;
}
}

// check if delete-array contains at least one item
if(count($delete > 0)){
// delete the items in the array from the database
mysqli_query($link, "DELETE FROM records WHERE filename IN('".implode("','", $delete)."'") or die(mysqli_error($link));
}

}

如果数据源不是你自己的,你也应该使用mysqli_real_escape_string();在进行查询之前转义数据。

关于php - 如何使用 php 加载 txt 文件并循环内容以查询数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54434886/

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