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

发布于 2025-01-05 05:25:02 字数 2278 浏览 0 评论 0 原文

我从我的脚本中提取了以下代码行。

    $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);

![屏幕截图]: https://i.sstatic.net/dOzSj.jpg

正如您从屏幕截图中可以看到,当选择一条或多条记录并单击删除按钮时,我希望将记录从数据库中删除,但希望将相应的sql插入语句写入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)< /代码>。这并没有完全发生。相反,先前写入的字符串会被新字符串覆盖。 我已经尝试了一遍又一遍,但只有最近的字符串才会覆盖旧的字符串。

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]: https://i.sstatic.net/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. 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). 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

空心空情空意 2025-01-12 05:25:02

很高兴 php 在 手册 中说 a+ (使用 a 应该足以满足您的需求):

开放阅读和写作;将文件指针放在文件末尾。如果该文件不存在,请尝试创建它。

但尝试运行此代码(称为 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);

它将生成以下输出:

Pos: 0
<?php
Pos: 6

您可以使用 fseek()

fseek( $fp, 0, SEEK_END);

或者使用 file_put_contents() 具有适当的参数:

file_put_contents( $file, $string, FILE_APPEND);

并且不要忘记检查您的文件权限以及文件是否已通过如下代码成功打开:

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

It's nice that php says in the manual that a+ (using a should be just enough for you):

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):

<?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( $fp, 0, SEEK_END);

Or use file_put_contents() with proper parameters:

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!');
}
溺ぐ爱和你が 2025-01-12 05:25:02

尝试使用 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);

Try to use file_get_contents and file_put_contents instead of fwrite, and append your queries to array or string:

$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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文