Using PHP, Load content from a CSV file and filter it to meet user input criteria and output in to a table

StackOverflow https://stackoverflow.com/questions/15258716

  •  18-03-2022
  •  | 
  •  

Domanda

Right, So I have a CSV file with data stored like this;

name,author,isbn,price
name,author,isbn,price
name,author,isbn,price
name,author,isbn,price

What I'm trying to do is to use a value in the URL which is user input to only display books by the corresponding author. For example getting a URL with a user input value such as;

/books.php?author=J.R.R. Tolkien

Will print the following in a tabular form;

The Hobbit, J.R.R. Tolkien, ISBN#, #Price
The Lord Of The Rings, J.R.R. Tolkien, ISBN#, #Price

I am not an expert in coding so all the help I can get would be appreciated. What I've managed so far is;

$author = $_GET['author'];
IF (strtolower ($author)==strtolower('J.R.R. TOLKIEN'))
{
echo '<table border=1>'; //start table
$handle = fopen("books.csv", "r");
while (($books = fgetcsv($handle, 1000, ',')) !== FALSE)

echo '<tr><td>',$books[0], //names
'</td><td>',$books[1], //authors
'</td><td>',$books[2], //ISBN
'</td><td>',$books[3], //price
'</td></tr>';
fclose($handle);
echo '</table>'; //end table
}

This code is functional but when I echo it all books are echoed instead of just those certain books of the selected author.

I've also tried $books[1] in the IF statement where it says J.R.R Tolkien but it does not seem to work.

I am at wits end. I am not an expert at this, so all the help would be appreciated. Thanks.

È stato utile?

Soluzione

You need to move the if statement to inside your loop, so that you are checking each book against the user's input.

I.e.

$author = $_GET['author'];
echo '<table border=1>'; //start table
$handle = fopen("books.csv", "r");
while (($books = fgetcsv($handle, 1000, ',')) !== FALSE)
{
    if (strtolower ($author)==strtolower($books[1]))
    {
        echo '<tr><td>',$books[0], //names
        '</td><td>',$books[1], //authors
        '</td><td>',$books[2], //ISBN
        '</td><td>',$books[3], //price
        '</td></tr>';
    }
}
fclose($handle);
echo '</table>'; //end table

You'll also need to add some logic for the case where there are no books which match the search parameters.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top