PHP - 检查用户输入是否与已转换为数组的文件中的值匹配

PHP - Check if user input matches value in file that has been converted to array

我有 3 个 .txt 文件(name.txt、cardnumber.txt、expirydate.txt)和 1 个 html 表单,只有一个输入(名称)。

我想读取用户输入,检查输入是否与 name.txt 中的任何行匹配,然后在所有 .txt 文件中显示字符串,其中包含找到输入的同一行 + 图像。

示例

name.txt:

John Doe
Jane Doe

cardnumber.txt:

1111 2222 3333 4444
4444 3333 2222 1111

expirydate.txt:

2025-12-31
1999-09-25

用户输入: Jane Doe

期望的输出:

Jane Doe 4444 3333 2222 1111 1999-09-25

这是我的代码:

<html>
<body>
<form method="POST" class="form">
        <h2>name: </h2><br>
        <input type="text" class="name" name="name" id="name"><br>
        <input type="submit" name="submit" id="submit" value="search">
    </form>

    <?php
    //convert files to arrays
    $file1 = 'name.txt';
    $file2 = 'cardnumber.txt';
    $file3 = 'expirydate.txt';
    $namefile       = file($file1);
    $cardnumberfile = file($file2);
    $expirydatefile = file($file3);

    //put user input to variable
    $search      = $_POST["name"];

    //display element with the same index in array namefile, cardnumberfile, and expirydatefile
    //index = index where user input found in namefile 
    while ($point = current($namefile)){
        if($point == $search){
            ?>
            <div class="card">
                <img src="images/img.png">
                <h2 class="cardname"> <?php echo $namefile[key($namefile)]; ?></h2><br>
                <h2 class="cardnumber"><?php echo $cardnumberfile[key($namefile)]; ?> </h2><br>
                <h2 class="expirydate"> <?php echo $expirydatefile[key($namefile)]; ?> </h2>
            </div>
            <?php ;}
         else{
            echo "No match\n";
        } next($namefile);}
        ?>
</body>
</html>

即使用户输入与 name.txt 中的一行匹配,程序仍然输出“不匹配”。

我必须使用文件,但禁止使用数据库。用array就可以了

我不知道代码有什么问题。请帮忙。

非常感谢。

file() 函数将保留行结尾,防止您轻松使用 == 与另一个字符串进行比较。您需要先trim()

无需每次检查一行不匹配时都说“不匹配”。如果你想在完成后说“不匹配”,请跟踪你是否找到了与 $found_match.

等变量的任何匹配项
<?php

//convert files to arrays
$file1 = 'name.txt';
$file2 = 'cardnumber.txt';
$file3 = 'expirydate.txt';
$namefile       = file($file1);
$cardnumberfile = file($file2);
$expirydatefile = file($file3);

//put user input to variable
$search      = $_POST["name"];

//display element with the same index in array namefile, cardnumberfile, and expirydatefile
//index = index where user input found in namefile 
$found_match = FALSE; // assume
while ($point = current($namefile)){
    if(trim($point) == $search){
        $found_match = TRUE;
        ?>
        <div class="card">
            <img src="images/img.png">
            <h2 class="cardname"> <?php echo $namefile[key($namefile)]; ?></h2><br>
            <h2 class="cardnumber"><?php echo $cardnumberfile[key($namefile)]; ?> </h2><br>
            <h2 class="expirydate"> <?php echo $expirydatefile[key($namefile)]; ?> </h2>
        </div>
        <?php
        break; 
    }
    next($namefile);
}
if ( ! $found_match ) {
    No match.
?>
<?php
}
?>