PHP - 检查 txt 文件中的值(如果已经存在)


PHP - Check a value inside txt file if already exist

HTML 代码:

<form action="insert.php" method="post">  
<label for="id-group">ID Gruppo</label>
<input type="text" id="id-group" name="id-group" />  
<br>
<label for="group-name">Nome del Gruppo</label>  
<input type="text" id="group-name" name="group-name" />  
<br>
<input type="submit" name="inserisci" value="Inserisci" />  
</form> 
<div style="width:400px;height:400px;background:green;">
<?php
$groups_database = 'groups.txt';
$riga = file($groups_database);
foreach($riga as $groups){
list($id, $nome_gruppo) = explode("|", $groups);
echo'
<div style="text-align:center;">
<a href="javascript:;" onClick="window.open(''https://m.facebook.com/groups/'.$id.'?view=info'',''TITLE'',''toolbar=no, scrollbars=yes, resizable=no, top=10, left=50, width=500, height=700'');">'.$nome_gruppo.'</a></br>
</div>';
}
?>
</div>

这是我在 txt 数据库中写入两个值的代码:(插入.php)

<?php
$bad_char = array("|");
$id = str_replace($bad_char, "", $_POST['id-group']);
$group = str_replace($bad_char, "", $_POST['group-name']);
$open = fopen("groups.txt","a+");
fwrite($open, $id."|".$group."'n");
fclose($open);
header("location: /");
exit;
?>

现在,我想知道如何检查数据库中是否已经存在一个值,如果已经存在,则会收到警报消息(不是丑陋的回声消息)。抱歉,我是 php 的初学者...希望得到您的帮助。问候。

尝试

<?php
session_start();
$id = preg_replace( '~'|~', '', $_POST['id-group']);
$group = preg_replace( '~'|~', '', $_POST['group-name']);
$messages = [];
$handle = @fopen("groups.txt","r+");
if( $handle )
{
    $i = 1;
    $exists = 0;
    while(( $str = fgets($handle)) !== false)
    {
      if( $id."|".$group."'n" === $str)
      {
        $exists ++;
      }
      $str = preg_replace( '~[^'|]~', '', $str);
      if( 1 !== strlen( $str ))
      {
        $messages [] = 'Line number ' . $i . ' - incorrect format';
      }
      $i++;
    }
    if ( ! feof($handle)) {
      $messages [] = 'fgets() error occured';
    }
    if( $exists )
    {
      $messages [] = 'Group already exists';
    } else {
      fwrite( $handle, $id."|".$group."'n");
    }
    fclose( $handle);
    if( ! empty( $messages))
    {
      $_SESSION ['errors'] = $messages;
    }
}
header("location: /");
exit();
?>

在"/"路由内:

<?php
session_start();
if( isset( $_SESSION ['errors'] ) && is_array( $_SESSION ['errors']))
{
  echo "<h2>Errors:</h2>";
  foreach( $_SESSION ['errors'] as $mess)
  {
    echo "<h3>{$mess}</h3>";
  }
  unset( $_SESSION ['errors']);
}
?>