Gymus
Gymus

Reputation: 21

Why $line = fgets("data/$f_handle") does not work

Okay, the situation looks simple enough, so what am I doing wrong?

$fname = "students.dat";
$f_handle = fopen("data/$fname", 'r');
$num_lines = count(file("data/$fname"));
for($x=0; $x<$num_lines; $x++) {
    $line = fgets("data/$f_handle");
    echo "Line $x: ($line)<br />"; //exit;
    if(strpos($line,$studentID)) {
    // Line has studentID
    echo "Line $x: ($line)($studentID)<br /> <br />";
    // Exit the loop if found
    break;      
}

My output is this:

Line 0: ()
Line 1: ()
Line 2: ()
Line 3: ()
Line 4: ()
Line 5: ()

I went flat-file, because my MySQL attempts were/are failing, $studentID is correct, and there are six lines to the data file. Any advice, please?

Upvotes: 1

Views: 56

Answers (1)

Marc Sch&#252;tz
Marc Sch&#252;tz

Reputation: 1061

$f_handle contains a resource object (a handle to the file you've just opened). Interpolating that in a string, as in "data/$f_handle" makes no sense. Just use fgets($f_handle) instead.

Apart from that though, there are several other problems in your code:

  • Counting the number of lines separately like you do is not the most useful approach, as it requires reading the file twice. Instead, use something like $x = 0; while(($line = fgets($f_handle)) !== false) { ... ; $x++; } instead.
  • strpos() returns false if there's no match, but it also returns 0 if the needle substring if found at the beginning of the haystack string. Both behave as false in an if condition. You should compare against false directly instead: if(strpos(...) !== false).
  • However, strpos() will likely not work here either. Imagine you're searching for a student with the ID 10, but the current line you're scanning has the ID 102. Your test will wrongly match on that line.
  • There is an opening brace after the if(), but no matching closing brace.

Upvotes: 2

Related Questions