phpUsing a foreach loop to iterate through an associative array and

I have a database table in Microsoft Access with three fields: partno, description, and quantity. However, when I try to retrieve the data and display it in an HTML table, I encounter an error message.

An issue occurred while trying to access the 'partno' field.

The PHP code I am currently using is:

<?php
 foreach($items as $row){
    $partno=$row['partno'];
    $desc=$row['description'];
    $qty=$row['quantity'];
  ?>
  <tr>
  <td><?=$partno?></td>
  <td><?=$desc?></td>
  <td><?=$qty?></td>
  </tr>

  <?php  
    }
    }
    if(!($items)){
  ?>
  <h3 style="color: red;">Item not found!</h3>
  <?php
    }
  ?>

In my attempt to troubleshoot the issue, I used the following command:

print_r($items);

Upon executing this command, I received the following output for the array $items:

Array ( 
    [partno] => BRZU 
    [0] => BRZU 
    [description] => CONTROL UNIT 
    [1] => CONTROL UNIT 
    [quantity] => 3 
    [2] => 3 
) 

Answer №1

It appears that the variable $items actually holds only one row of data. When iterating through it with a foreach loop, the variable $row will contain the values BZRU, BZRU, CONTROL UNIT, 2, 3.

Perhaps you were anticipating an array of multiple arrays, which can be iterated over using your foreach loop.

Answer №2

To begin, ensure that the array named itemsList is not empty before proceeding with the loop.

<?php
     if(is_array($itemsList) && count($itemsList) > 0){//checking if there are any items to iterate through
       foreach($itemsList as $product){
        $partNumber=$product['partno'];
        $description=$product['description'];
        $quantity=$product['qty'];
      ?>
      <tr>
      <td><?=$partNumber?></td>
      <td><?=$description?></td>
      <td><?=$quantity?></td>
      </tr>

      <?php  
        }
      } else {
          ?>
      <h3 style="color: red;">Item could not be found!</h3>
      <?php
        }
      ?>      

Answer №3

It appears that your reasoning is flawed. It is imperative to verify the emptiness of $items before embarking on any iteration.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for showcasing multiple tables based on certain criteria

Hey there, I'm currently working on an inventory page where I want to display multiple tables based on department values. The goal is to have each department in its own table instead of all merged into one. It would definitely make the page easier to ...

Saving information from MySQL database into a CSV file using PDO through a web browser

I'm struggling with a form that writes data to a MySQL database. My goal is to allow users to download their submitted data in CSV format once they complete the form. Currently, my code is displaying the database contents on the browser instead of ge ...

How can one obtain a distinct identifier retroactively?

One thing that I am working on is changing button images upon clicking, but this isn't the main issue at hand. Each button corresponds to unique information retrieved from the database, and when clicked, the button should change and send the appropria ...

Step-by-Step Guide for Uploading an Entire Folder and Its Contents

I have been working on a code to upload multiple files, but now I am facing the challenge of uploading an entire folder with multiple files and possibly subfolders containing even more files. Currently, I am utilizing JavaScript for obtaining the files and ...

What is the process for activating the template selection in the Wordpress toolbar while working on a unique theme design?

As I work on creating a custom Wordpress theme, I'm keen to enable the option for users to select their own page template in the admin area. Some themes include this feature while others do not, as illustrated below: Themes without support: https:// ...

Use JavaScript to upload a JSON file containing arrays into separate tabs

Looking for help with incorporating JSON data into an HTML template that features tabs and a gallery? Take a look at my setup below: <div class="tab"> <button class="tabLinks" onclick="openDiv(event, 'overview'); appendData()" id= ...

The variables do not align with the number of parameters specified in the prepared statement

As I work on developing an application, I encounter an issue with the login page where I need to verify if a user exists in the database. Although my code seems correct as I only check for the name, I am facing an error when implementing the prepared state ...

Is there a risk of overloading the server and browser by making constant AJAX calls at regular intervals?

I am in the process of creating a website that requires notifications. I want to use AJAX to continuously check for updates in my database where notifications are stored at regular intervals. My concern is, with multiple users all accessing the AJAX call ...

show information retrieved from database according to the drop-down menu selection

Can anyone assist me with this query? I have a drop-down menu that includes "Shop A" and "Shop B". Shop A has a value of 1, and Shop B has a value of 2. When I select Shop A from the dropdown, I want to display the data from the database as a table specifi ...

Joomla update query malfunctioning - seeking resolution

Currently, I am in the process of developing a Joomla extension and I am attempting to update entries within my Joomla extensions database table using the code snippet below in my model: $this->_db->setQuery( $this->_db->getQu ...

Unable to retrieve file from Alias directory using the download script

Currently, I am developing a download script. The PHP files are stored in the xampp htdocs directory, while the folder containing the actual files is on an external HDD. An Alias has been configured for the external drive: <Directory "h:/Filme"> Op ...

Encountering a 500 error when trying to execute an HTML form action directed

As I begin my journey with PHP, I am eager to make my HTML/javascript form capable of sending emails via PHP. In the same HTML document, below is the relevant code: (For privacy reasons, the web address has been changed, but it is the same in reality.) & ...

Is it possible to customize font sizes when printing with PHP?

As an employee at a school, I am in the process of creating a wizard-style interface for our helpdesk. Students will use a tablet to input their name and select the issue they are facing, resulting in a ticket being generated in our system. We have a shar ...

Counting the days: how to calculate without using negative numbers

After performing the calculation, the result shows -30. Is there a way to eliminate the negative sign and get 30 instead? $days = (strtotime(date("Y-m-d")) - strtotime($info['expiredate'])) / (60 * 60 * 24) echo abs($days); Any suggestions on ...

Issue encountered in CakePHP 3.5 when using the Crud plugin (Uncaught Exception in CrudComponent.php)

While trying to implement the plugin friendsofcake/crud, version 5.4.1, on a fresh installation of CakePHP 3.5 with the Api, ApiPagination and ApiQueryLog listeners, I encountered an issue. My setup includes PHP 7.0 on Ubuntu. Following the installation i ...

Verify if the data in the Express request is an array

Recently, I've been working on an Express 3.x API server and facing the challenge of implementing support for batch requests at a specific endpoint. Despite not having the control to upgrade to 4.x, I am determined to find a solution. Currently, the e ...

What could be causing the fputcsv function to not write to my CSV file?

For some reason, I've encountered an issue while attempting to write to a .csv file using PHP. The file remains blank and no data is being added. Initially, an AJAX post request is sent to addComment.php, where the intention is to append the POST data ...

Ways to conceal buttons according to your 'occupation'?

I am currently developing an application and I would like to have certain buttons displayed based on the user's $job. There are four job roles stored in mysql databases: student teacher staff principal, The signup button should only be visible to te ...

I encountered a PHP file error while working on my school project

A warning message was generated in file C:\wamp\www\probeer\opvragen.php on line 112 regarding an undefined variable (upid). Call Stack # Time Memory Function Location 1 0.0007 264840 {main}( ) ..\opvragen.php:0 T ...

Creating a responsive form with live updating using ReactJS and utilizing double inputs for better

Currently, I am working on updating a form with double input fields. The aim is for users to be able to click an 'add' button and update the state with their values, while ensuring that the two input fields are "connected". To better illustrate m ...