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

时间:2019-01-30 06:57:33

标签: php mysql

我有一段代码我只是无法正常工作。我正在尝试遍历大约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);
?>

3 个答案:

答案 0 :(得分:1)

首先:始终避免在循环内进行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();。在查询之前先转义数据。

答案 1 :(得分:0)

您需要在'$line'中加上引号,以使该变量不被视为列名

DELETE FROM images WHERE images_file_name like '$line'

尽管您可以使用sql注入,但是您必须阅读准备好的语句

答案 2 :(得分:0)

在注释中使用(非常)有用的建议并整理一下代码,这使用准备好的语句等,仅在最后关闭链接(When should I close a database connection in PHP?上的一些有用信息)...

$handle = fopen("corrupt.txt", "r");

if ($handle) {
    $link = mysqli_connect("localhost", "user", "pass", "listings"); 
    if($link === false){
        die("ERROR: Could not connect. " . mysqli_connect_error());
    }
    $sql = "DELETE FROM images WHERE images_file_name = ?";
    if( !$stmt = mysqli_prepare($link, $sql) ){
        die("ERROR: Could not prepare. " . mysqli_error($link));
    }
    mysqli_stmt_bind_param($stmt, "s", $line);
    while (!feof($handle)) {
        $line = trim(fgets($handle));
        if(!mysqli_stmt_execute($stmt)){
            echo "ERROR: Could not able to execute $sql. "
                . mysqli_error($link);
        }
    }
    mysqli_close($link);
    fclose($handle);
} else {

}

还请注意,我已将SQL从like ...更改为= ...,前提是该名称与内容完全匹配。