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

时间:2016-02-09 14:42:34

标签: php

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数据库中写两个值的代码: (insert.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的初学者... 希望在你的帮助下。问候。

1 个答案:

答案 0 :(得分:0)

尝试

<?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']);
}
?>