I have 3 .txt files (name.txt, cardnumber.txt, expirydate.txt) and 1 html form with one input (name).
I want to read the user input, check if the input matches any line in name.txt, and then display string in all .txt files with the same line where the input found an image.
EXAMPLE
name.txt:
John Doe
Jane Doe
cardnumber.txt:
1111 2222 3333 4444
4444 3333 2222 1111
expirydate.txt:
2025-12-31
1999-09-25
user input:
Jane Doe
desired output:
Jane Doe 4444 3333 2222 1111 1999-09-25
Here's my code:
<html>
<body>
<form method="POST" >
<h2>name: </h2><br>
<input type="text" 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 >
<img src="images/img.png">
<h2 > <?php echo $namefile[key($namefile)]; ?></h2><br>
<h2 ><?php echo $cardnumberfile[key($namefile)]; ?> </h2><br>
<h2 > <?php echo $expirydatefile[key($namefile)]; ?> </h2>
</div>
<?php ;}
else{
echo "No match\n";
} next($namefile);}
?>
</body>
</html>
Even though the user input matches with a line in name.txt, the program still outputs "No match".
I must work with files, but using database is prohibited. It's okay to use array.
I don't know what is wrong with the code. Please help.
Thank you so much.
CodePudding user response:
The file()
function will retain line endings, preventing you from easily using ==
to compare with another string. You need to trim()
first.
There is no need to say "no match" every time you check a line and it doesn't match. If you want to say "no match" after you are done, keep track of whether you found any matches with a variable like $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 >
<img src="images/img.png">
<h2 > <?php echo $namefile[key($namefile)]; ?></h2><br>
<h2 ><?php echo $cardnumberfile[key($namefile)]; ?> </h2><br>
<h2 > <?php echo $expirydatefile[key($namefile)]; ?> </h2>
</div>
<?php
break;
}
next($namefile);
}
if ( ! $found_match ) {
No match.
?>
<?php
}
?>