简体   繁体   English

如何防止php fwrite()覆盖文件上的一行文本?

[英]how to prevent php fwrite() from overwriting a line of text on file?

I have extracted following lines of code from my script. 我从脚本中提取了以下代码行。

    $i=0;
    $j=0;
    $fp=fopen('C:\xampp\htdocs\Lib_auto_project\Deleted_Records\delete_log.sql','a+');// File where the string is to be written
    foreach($_POST as $temp)//repeat for all the values passed from the form
    {
        if($j==0)
          {     
               $result_set=$mysqli->query("select * from {$_SESSION['table_name_1']} where Copyid=$temp");
               $result_set=$result_set->fetch_array(MYSQL_BOTH);    
               ++$j;

           }
        if($temp!='Drop')// Drop is simply the value of submit buttom
         {
            $date=mysql_query("select now() as current_date_time") or die(mysql_error());
            $date=mysql_fetch_array($date,MYSQL_BOTH);
            $result="\n"."INSERT INTO delete_book_log  // this is the string begining with line break and followed by sql insert statement
                          VALUES(
                                 '{$result_set["Bid"]}',
                                 '$temp',
                                 '{$result_set["Name"]}',
                                 '{$result_set["Publication"]}',
                                 '{$result_set["ISBN"]}',
                                 '{$result_set["Author"]}',
                                 '{$result_set["Edition"]}',
                                 'in',
                                 '{$result_set["Book_Baseid"]}',
                                 '{$date['current_date_time']}'
                                 );";
              fflush($fp);
              fwrite($fp,$result);
              $mysqli->query("Delete from {$_SESSION['table_name_1']} where copyid=$temp");
              $i++;
          }

      }
      fclose($fp);

![screen shot]: http://i.stack.imgur.com/dOzSj.jpg ![屏幕截图]: http//i.stack.imgur.com/dOzSj.jpg

As you can see from the screen-shot, when one or more of the records are selected and the drop button is clicked, I want the records to be deleted from the database but want the corresponding sql insert statements to be written into a file(C:\\xampp\\htdocs\\Lib_auto_project\\Deleted_Records\\delete_log.sql) .For that to happen I have written the above piece of code. 从屏幕快照中可以看到,当选择一个或多个记录并单击下拉按钮时,我希望从数据库中删除记录,但希望将相应的sql插入语句写入file(C:\\xampp\\htdocs\\Lib_auto_project\\Deleted_Records\\delete_log.sql) 。为此,我编写了上面的代码。 Now the problem is when I select the records and drop them all goes as desired. 现在的问题是,当我选择记录并将其全部删除时,一切都按需进行。 When I do the same any other instant I want similar sql insert strings, stored as shown above in $result, appended to the end of the file(C:\\xampp\\htdocs\\Lib_auto_project\\Deleted_Records\\delete_log.sql) . 当我执行其他任何操作时,都希望将类似的sql插入字符串(如上所示存储在$ result中)附加到file(C:\\xampp\\htdocs\\Lib_auto_project\\Deleted_Records\\delete_log.sql) This does not quite happen. 这并没有发生。 Rather the previously written strings get overwritten by the new one. 而是先前写入的字符串会被新的字符串覆盖。 I have tried it over and over but only the recent strings get overwrite the old ones. 我已经反复尝试过,但是只有最近的字符串会覆盖旧的字符串。

It's nice that php says in the manual that a+ (using a should be just enough for you): php在手册中a+ (使用a对您来说就足够了)是一件很不错的事情:

Open for reading and writing; 开放供阅读和写作; place the file pointer at the end of the file. 将文件指针放在文件末尾。 If the file does not exist, attempt to create it. 如果该文件不存在,请尝试创建它。

but try to run this code (called test.php ): 但是尝试运行以下代码(称为test.php ):

<?php    
$fp = fopen( 'test.php', 'a+') or die( 'Cannot open!');
echo 'Pos: ' . ftell($fp) ."\n";
echo fgets($fp);
echo 'Pos: ' . ftell($fp) ."\n";
fclose( $fp);

it'll generate this output: 它将生成以下输出:

Pos: 0
<?php
Pos: 6

You may either use fseek() : 您可以使用fseek()

fseek( $fp, 0, SEEK_END);

Or use file_put_contents() with proper parameters: 或使用带有适当参数的file_put_contents()

file_put_contents( $file, $string, FILE_APPEND);

And don't forget to check your file permissions and whether file was opened successfully by code like this: 并且不要忘记检查您的文件权限以及是否通过以下代码成功打开了文件:

if( !$fp){ 
    die( 'File cannot be opened!');
}

Try to use file_get_contents and file_put_contents instead of fwrite, and append your queries to array or string: 尝试使用file_get_contents和file_put_contents而不是fwrite,并将查询附加到数组或字符串:

$fp=file_get_contents('C:\xampp\htdocs\Lib_auto_project\Deleted_Records\delete_log.sql');// File where the string is to be written
foreach($_POST as $temp)//repeat for all the values passed from the form
{
    if($j==0)
      {     
           $result_set=$mysqli->query("select * from {$_SESSION['table_name_1']} where Copyid=$temp");
           $result_set=$result_set->fetch_array(MYSQL_BOTH);    
           ++$j;

       }
    if($temp!='Drop')// Drop is simply the value of submit buttom
     {
        $date=mysql_query("select now() as current_date_time") or die(mysql_error());
        $date=mysql_fetch_array($date,MYSQL_BOTH);
        $result="\n"."INSERT INTO delete_book_log  // this is the string begining with line break and followed by sql insert statement
                      VALUES(
                             '{$result_set["Bid"]}',
                             '$temp',
                             '{$result_set["Name"]}',
                             '{$result_set["Publication"]}',
                             '{$result_set["ISBN"]}',
                             '{$result_set["Author"]}',
                             '{$result_set["Edition"]}',
                             'in',
                             '{$result_set["Book_Baseid"]}',
                             '{$date['current_date_time']}'
                             );";
          $fp .= $result . "\r\n";
          $mysqli->query("Delete from {$_SESSION['table_name_1']} where copyid=$temp");
          $i++;
      }

  }
  file_put_contents($fp);

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

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