-1

I am trying to retrieve a row from my csv file.

For example:

//my csv file
Serial No., Name, Type, Category
12345, John, SG, Old
23456, Mary, MY, New

I am trying searching by serial number. What I want to achieve is something like this.

search: 12345
results: 12345, John, SG, Old

I tried using the method below

<?php

//from the previous page of my search bar
$sn = $_POST["sn"];

$result  = [];
if (($handle = fopen("gameDirectory.csv", "r")) !== FALSE) {
    
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        
      if($data[1] == $sn) 
          
          print_r($data);
        
    }
    
    fclose($handle);

  
}
?>

It is not showing anything after i click search.

Joey Kang
  • 11
  • 2
  • Did you try to `var_dump`/`print_r` `$data` before using it and see if it contains the data you expect? – Ali Alwash Jul 30 '20 at 19:34
  • what do you mean? Do you mean my whole CSV file? or just the row I am searching for? My previous page shows a table of my whole CSV file.@AliAlwash – Joey Kang Jul 30 '20 at 20:10
  • 1
    I guess what the previous commenter meant was to check that you are reading lines OK - check what `$data` looks like before testing for a match. You should also of course verify `$_POST["sn"]` looks like what you expect. Side note - convention would suggest [using `GET` for your search query, not `POST`](https://stackoverflow.com/questions/3477333/what-is-the-difference-between-post-and-get). – Don't Panic Jul 30 '20 at 23:04

1 Answers1

0

An array always start at 0.
Change $data[1] to $data[0].

Better code will nomalize both variable, somthing like :

<?php

//from the previous page of my search bar
$sn = intval($_POST["sn"]);

$result  = [];
if (($handle = fopen("gameDirectory.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
      if(intval($data[0]) == $sn)
          print_r($data);
    }
    
    fclose($handle);
}
Bazaim
  • 2,216
  • 1
  • 7
  • 20