Hi~ I’m trying to put info from my books txt file into an array and display them on my page using a foreach loop, but I’m having some issues.
index.php
<?php
session_start();
$title = "Great Gubal Library";
$description = "Online bookstore";
include ('include/header.php');
require('include/functions.php');
//create courses_taken arry if necessary
if (!isset($_SESSION['book_cart'])) {
$_SESSION['book_cart'] = array();
}
//check if user has clicked a completed course button
if (isset($_POST['book_isbn'])) {
$_SESSION['book_cart'][] = $_POST['book_isbn'];
unset($_POST['book_isbn']);
}
?>
<body>
<header>
<h1>Great Gubal Library</h1>
<h2> Welcome!</h2>
</header>
<main>
<?php
$inventory = get_inventory();
foreach ($inventory as $book) { ?>
<figure>
<img src="/imgs/books">
<figcaption>
<?php echo $inventory['book_title']; ?>
<?php echo $inventory['book_author']; ?>
<?php echo $inventory['book_price']; ?>
<?php echo $inventory['book_quantity']; ?>
<form action="index.php" method="post">
<input type="hidden" name="book_isbn" value="<?php echo $book['book_isbn']; ?>">
<input type="submit" value="Checkedout">
</form>
</figcaption>
</figure>
<?php } ?>
</main>
<aside>
</aside>
<?php
include ('include/footer.php')
?>
</body>
</html>
function.php
<?php
function get_inventory() {
//open file for reading
@ $fp = fopen("/book_list.txt", 'r');
if (!$fp) {
echo "<p>No books found.</p>";
}
else {
//read info for the first book
$book = fgets($fp, 999);
while (!feof($fp)) {
//parse the book
$book_title = strtok($book, ",");
$book_author = strtok(",");
$book_isbn = strtok(",");
$book_price = strtok(",");;
$book_quantity = strtok("");
//put the book in the array
$inventory_array[] = array('book_isbn'=>$book_isbn,
'book_title'=>$book_title,
'book_author'=>$book_author,
'book_price'=>$book_price,
'book_quantity'=>$book_quantity);
//read the next book
$book = fgets($fp, 999);
}
fclose($fp);
}
return $inventory_array;
}
?>
This is how the txt file is formatted:
Here are my errors:
No books found.
Notice : Undefined variable: inventory_array in C:\xampp\htdocs\assign2\include\functions.php on line 35
Warning : Invalid argument supplied for foreach() in C:\xampp\htdocs\assign2\index.php on line 29