Expanding query with additional JOIN and retrieving table column headings

I'm currently developing a function to convert data into CSV format, but I've hit a roadblock.

At the moment, the function is fetching data from two tables and saving it to a CSV file in a single line for each order, including invoice and customer details.

However, I also need to retrieve invoice_items by ID (which may involve looping through multiple items) and add them to the query. Additionally, I'm unsure how to set column titles for the output.

Ideally, the final output should be structured like this:

|invoice details customer details | invoice items

                               LIST ITEM

                               LIST ITEM

                               LIST ITEM

Instead of the current format:

invoice details | customer details | invoice items LIST ITEM LIST ITEM LIST ITEM

A sample output with real data and titles might look something like this:

id | invoice number | amount | name | address | invoice items (and list below this part)

As for the PHP code, here is what I have so far:

header("Content-type: text/csv"); 

    // Handle any connection errors
    if ($mysqli->connect_error) {
        die('Error : ('.$mysqli->connect_errno .') '. $mysqli->connect_error);
    }

    $file_name = 'invoice-export-'.date('d-m-Y').'.csv';   // Define file name
    $file_path = 'downloads/'.$file_name; // Define file path

    $file = fopen($file_path, "w"); // Open file in write mode
    chmod($file_path, 0777);    // Set file permissions

    $query_table_columns_data = "SELECT * 
                                    FROM invoices i
                                    JOIN customers c
                                    ON c.invoice = i.invoice
                                    WHERE i.invoice = c.invoice
                                    ORDER BY i.invoice";

    if ($result_column_data = mysqli_query($mysqli, $query_table_columns_data)) {

        // Fetch table fields data
        while ($column_data = $result_column_data->fetch_row()) {
            $table_column_data = array();
            foreach($column_data as $data) {
                $table_column_data[] = $data;
            }

            // Format array as CSV and write to file pointer
            fputcsv($file, $table_column_data, ",", '"');
        }

    }

Answer №1

It seems that you are looking to retrieve invoice items by joining with another table.

In your current query, it appears that the tables are being joined incorrectly. It looks like you are connecting the customers and invoices tables based on the invoice itself. Ideally, a customer can have multiple invoices, but an invoice is associated with only one customer. Therefore, I would suggest storing the relevant customer ID in the invoice table and then performing a join based on that.

You can fetch the details using a query similar to this:-

SELECT i.id,
    i.invoice_number,
    i.amount,
    c.name,
    c.address,
    ii.invoice_item
FROM invoices i
INNER JOIN customers c
ON c.id = i.customer_id
INNER JOIN invoice_items ii
ON ii.invoice_id = i.id
ORDER BY i.invoice

Instead of using SELECT *, it's recommended to specify the column names for better clarity. If needed, you can alias the column names for readability.

If you require a list of titles extracted from the column names dynamically, consider switching from mysqli_fetch_row to mysqli_fetch_assoc. This will return the column names which you can process to output accordingly.

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

Unraveling JSON data retrieved from a MySQL query

After successfully encoding a MySQL result from PHP into JSON, I am now faced with the task of decoding it using JavaScript. Let's assume that my string returned is: [{"0":"x","1":"z"},{"0":"xs","1":"zz"}] I would appreciate some guidance on how to ...

Error in Reactjs in production mode: net::ERR_CERT_COMMON_NAME_INVALID

My Reactjs application is deployed on a Linux server and can be access at I am using PHP APIs to fetch data, which are also hosted on the same server and accessible through However, when trying to fetch data from the API, I receive an error in the consol ...

Retrieve JSON data from a PHP script to be used in an Angular scope

I am attempting to retrieve JSON data from a PHP file to use in an Angular controller. I have used json_encode(pg_fetch_assoc($result)); within the PHP file and when I check with console.log($scope.contents); in the Angular controller, the JSON data is ret ...

The timezone of the iCalendar event does not correspond to the user's timezone, causing

When I send an event to MS Outlook via email, the event time displayed at the user end is different from what I originally sent. I am also looking for a way to support iCalendar events across various applications such as MS Outlook and Google Calendar. I ...

Unable to remove MySQL row using AJAX and JSON

After successfully inserting rows into my MySQL database, I encountered an issue when trying to DELETE a row using the same logic. Despite following similar steps, I am unable to delete the specified row by its ID. I need assistance in identifying what is ...

Trouble with Spaces in FPDF PHP Library on UNIX Operating System?"

I have encountered a strange issue while using the FPDF library to create a PDF document from MySQL tables. Everything works perfectly fine on my Windows computer, but when I try running the script on my Ubuntu machine, all the spaces disappear inexplicabl ...

Tips on working with an array received from a PHP script through AJAX

I've been stuck with this issue for the past few hours and I'm hoping to find a solution here. What I'm attempting to do is something like the following: PHP: $errorIds = array(); if(error happens){ array_push($errorIds, $user['user ...

Developing a REST API for a component with 18 interconnected elements

Currently, I am developing a REST API to expose a table to an Angular frontend, and I've encountered a unique challenge: The data required for display is spread across 10 different tables besides the main entity (referred to as "Ticket"). Retrieving t ...

Passing boolean data from JQuery to PHP can be done by sending the data

When using ajax to send data from jquery to php, I am encountering an issue where Boolean data sent through jquery is received by php as a string. However, I want the Boolean data to be recognized as Boolean on the php end. Below is the code snippet: $.a ...

Transform a string value into an array by splitting using line breaks

Here's a scenario: $string = " test1 test2 test3 test4 test5"; I'm looking to transform it into an array like this: array('test1','test2','test3' and so on) Any ideas on how I can achieve that? ...

Updating a MySQL table with a list of values

I am having issues with a form that is supposed to extract data from a MySQL table into a form. Each row has a menu for selecting a value, and I want to update the MySQL database with the selected values for each row when the 'Apply To All' butto ...

Having trouble with sending information to the PHP server, unable to determine the root cause

Can someone help me figure out why the data from a form being sent to a php script for sending an email isn't working correctly? It's part of a template code but I suspect there might be an error. Specifically, I believe the {'userName' ...

Guide on adjusting PHP variable values and updating functions with ajax requests

One of my functions determines dates based on a variable For example: $modification = "+1 Week" function updateCalendar($change){ $month = array("January","February","March","April","May","June","July","August","September","October","November","Dece ...

Using regular expressions in PHP to extract an array

Currently, I am in the process of converting shortcode details from an outdated CMS that I am utilizing. Within some article content, I am required to extract the ID from existing callouts. {image id="27411" shape="landscape" align="right"} It is possibl ...

Employing the GET method to retrieve the values of two text inputs

I'm struggling to retrieve the values from two text input fields: <form action="search.php"> <input type="text" name="q1"> <input type="text" name="q2" > <input type="submit" name="submit" value="Search" /> </form> On t ...

Server response not being awaited by Ajax call

Currently running WAMP v.2.5 on a Windows10 system for my PHP project connected to a MySQL DB that involves multiple AJAX calls, all functioning correctly. However, there is one specific call that keeps throwing an 'Unexpected end of input' error ...

Generating AWS presigned URLs for objects stored in an S3 bucket

Our team uploads various types of content to a secure S3 bucket. When we generate and access presigned URLs for MP4 videos and images, everything works smoothly in the browser. However, when trying to access SWF and PDF files, the browser prompts us to dow ...

Querying for MySQL data within specific time intervals of 5 to 10 minutes and 1 to 2 hours

I need help creating a MySQL query to display the number of users who have spent time in the showroom within the last 5 minutes, 30 minutes, and 1 hour. The timestamps are recorded as entry_user and exit_user. Can someone suggest how I can achieve this to ...

When attempting to access the length of a JSON array, it results in undefined

I recently received a JSON encoded array from an AJAX call that looks like this: {"country":{"0":"United States of America","United States of America":{"states":{"0":"Alaska","Alaska":{"cities":["Adak","Akiachak","Akiak","Akutan","Alakanuk"]}}}}} Below ...

Save a record and establish a connection with another record without saving the second record again

Currently, I am in the process of developing a front-end application using Durandal/Knockoutjs along with a web service backend created with Symfony2 that utilizes Doctrine for database access. In my project, I have two entities that are related in a one- ...