Search code examples
phphtmlformscsvstrpos

php csv skips one line on submit


There seems to be some issue with the code where the result is skipped with one line.

For example, if I write: 642641 the result should be: "642641","testgatan 1" but instead, it's showing: "762755","testgatan 2"

How can I fix so it actually get the input submitted?

I got a link for you to see what I mean: http://snaland.com/herestheidnummer/test.html

Here's the csv:

ID,Gata
"642641","testgatan 1"
"762755","testgatan 2"
"346468","testgatan 3"
"114564","testgatan 4"
"758925","testgatan 5"

I used the php code from Find if a value exist in a CSV file with PHP by Fred -ii-

And modified it like this:

<?php
$search      = $_GET['subject'];
$lines       = file('http://snaland.com/herestheidnummer/anlaggningsnmr.csv');
$line_number = false;

while (list($key, $line) = each($lines) and !$line_number) {
   $line_number = (stripos($line, $search) !== FALSE);

}

if($line_number){

   echo "Found result: " .$line;

}

else{
   echo "Can't find result: " .$search;
}

?>

Html form:

<form name="form" action="http://snaland.com/herestheidnummer/verifiera.php" method="get">
  <input type="text" name="subject" id="subject" value="000000">
  <input type="submit" value="Submit">
</form>

Solution

  • Your problem is the condition in the while loop. The assignment to key and list get executed before the check of !$line_number. It should work ff you swap both conditions like this

    while (!$line_number and list($key, $line) = each($lines) ) {
       $line_number = (stripos($line, $search) !== FALSE);
    }