Adding several entries into mysql with the assistance of php

I've been attempting to input multiple records into my database table, but every time I try, all I see are zeros(0) inserted into the fields. Here's what I attempted: I used a foreach loop for insertion, but unfortunately it doesn't seem to be working for me. Is there an easier way to accomplish this task? Thank you

The html

<form method="post" action="data_handlers/purchase_entry_process.php">
    <table>
    <thead>
    <tr class="titlerow">
    <th>Item name</th>
    <th>Quantity</th>
    <th>Purchase Price</th>
    <th>Amount</th>
    <th>Description</th>
    </tr>
    </thead>
        <tr>
        <td class="col-md-3"><select name="item_code[]">
        <option></option>
        <?php
        $tempholder = array();
        $query = $link->query("SELECT * FROM items");
        $nr = mysqli_num_rows($query);
        for($i=0; $i<$nr; $i++) {
        $row = mysqli_fetch_array($query);
        if(!in_array($row['item_code'],$tempholder)) 
        {
        echo"<option value=\"{$row['item_code']}\" >{$row['item_name']}</option>";
        }
        }  
        ?>
        </select></td>
        <td><input type="text" name="qty"></td>
        td><input type="text" name="purchase_price"></td>
        <td><input type="text" name="sub_total"></td>
        <td><input type="text" name="description"></td>                     
        </tr>
        <tr>
        <td class="col-md-3"><select name="item_code[]">
        <option></option>
        <?php
        $tempholder = array();
        $query = $link->query("SELECT * FROM items");
        $nr = mysqli_num_rows($query);
        for($i=0; $i<$nr; $i++) {
        $row = mysqli_fetch_array($query);
        if(!in_array($row['item_code'],$tempholder)) 
        {
        echo"<option value=\"{$row['item_code']}\" >{$row['item_name']}</option>";
        }
        }  
        ?>
        </select></td>
        <td><input type="text" name="qty"></td>
        td><input type="text" name="purchase_price"></td>
        <td><input type="text" name="sub_total"></td>
        <td><input type="text" name="description"></td>                     
        </tr>
    </table>
    </form>

php

$item_code = $_POST['item_code'];
$qty = $_POST['qty'];
$pur_price = $_POST['purchase_price'];
$sub_total = $_POST['sub_total'];
$desc = $_POST['description'];

foreach($item_code as $item_codes);
$insert_inventory = $link->query("INSERT INTO inventory VALUES ('NULL','$item_codes','$qty','$pur_price','$qty','$desc','$sub_total')");

Answer №1

If you want to extract the quantity, price, sub_total, and description from all fields, consider converting them into arrays just like you did with item_code.

<td><input type="text" name="qty[]"></td>
<td><input type="text" name="purchase_price[]"></td>
<td><input type="text" name="sub_total[]"></td>
<td><input type="text" name="description[]"></td>  

To process this in PHP for database queries, you can follow a similar approach like this:

<?php
    // Prepare the query
    $query = "INSERT INTO inventory VALUES ";

    // Loop through each entry
    foreach ($_POST['item_code'] as $key => $value) {

        // Check if an item has been selected
        if (!empty($value) && $value != "") {
            $query .= ($key > 0 ? ", " : "");
            $query .= "(NULL, '" . $value . "', '" . $_POST['qty'][$key] . "', '" . $_POST['purchase_price'][$key] . "', '" . $_POST['sub_total'][$key] . "', '" . $_POST['description'][$key] . "')";
        }
    }

    // Example output of $query
    // INSERT INTO inventory VALUES (NULL, '1', '1', '11', '111', '1111'), (NULL, '2', '2', '22', '222', '2222')
?>

It's also recommended to perform variable escaping to prevent SQL injection attacks.

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

NodeJS Express throwing error as HTML on Angular frontend

I am currently facing an issue with my nodejs server that uses the next() function to catch errors. The problem is that the thrown error is being returned to the frontend in HTML format instead of JSON. I need help in changing it to JSON. Here is a snippe ...

Is there a way to display multiple images in a JSON message object?

If you're looking for a fun way to generate random dog images, then check out my DogAPI image generator! Simply enter a number between 1-50 into the form text box, hit send, and watch as it displays that amount of random dog photos. I'm almost t ...

Having difficulty utilizing the express.session module in conjunction with HTTPS

I need to implement authentication and session creation on a HTTPS static website using expressjs. Here is the code snippet: app.js: // Set up the https server var express = require('express'); var https = require('https'); var http ...

Retrieve JSON data from a PHP script

Hey there everyone, I'm new to working with JSON and I need some help. I have data (an array) that was sent from a PHP file in encoded format, and all I want to do is simply get this data and display an alert with it. The object sent from the PHP fi ...

Passing data to server-side PHP script using AJAX technology

Currently, I'm facing an issue with passing variables to a PHP script using onclick. It seems that I am making a mistake somewhere. To demonstrate the problem, let's say I have the following code snippet in my main page: <img src="myImage.jp ...

Retrieving specific user data from a MySQL database in PHP can be achieved by using the logged-in user's information as

I've been struggling to retrieve specific user data for the logged-in user. While I can fetch all data with my current code, I need to narrow it down to just one user. I attempted using WHERE username="$username" and various other approaches, but non ...

What is the best method for integrating opensea-js using a script tag in a vanilla HTML/JS environment?

Is there a way to incorporate opensea-js into an html/js project that does not rely on node.js? The source code for opensea-js is only available on github and npm at https://github.com/ProjectOpenSea/opensea-js I came across this link: However, when I tr ...

How can strings of dates be arranged in MM/DD/YYYY order?

Is there a correct way to sort these dates in descending order? I've attempted using arr.sort() and arr.sort().reverse(), searched extensively on stack overflow, but still cannot find a solution. Every attempt at sorting them seems to be incorrect. [ ...

Utilize PHP to communicate with Urban Airship by sending a message

As an iPhone developer, I am currently building an application that requires sending notifications to devices where the app is installed. I have successfully integrated Urban Airship for this purpose. Now, my next goal is to send messages from a CMS usin ...

Preserve input values after form submission in <?php> code block

I would like to retain form values after submission. I have come across some techniques that claim to do just that: However, when I try to run the HTML file, I encounter two issues: firstly, the code does not function as intended and secondly, PHP snippet ...

Introducing a grid view option on the customer edit page within the admin interface by adding a new tab

My goal is to add a custom tab to the customer edit page. When this tab is clicked, I want a Grid view to open with sorting and filtering functionality. Currently, I am able to display data in a grid. However, when I include 'filter' => tr ...

Finding it difficult to grasp the concept of unset() function when using indirect references in PHP

Exploring the nuances of unset() in PHP version 5.6, especially in cases involving indirect references has been my recent focus. By using unset(), the memory allocated for a variable is freed up only if there are no other references to its value. In one ...

Keeping the header fixed on a sticky div (tocbot)

While working on my website, I decided to implement a Table of Contents section using tocbot. However, I encountered an issue where the Title I added above the table doesn't stay fixed when scrolling. https://i.stack.imgur.com/vCm1K.gif Here's ...

Is there a way for me to update a Link To containing a parameter by using history.push with a parameter inside a table cell?

Hey there! I'm working on some code and wondering if it's doable to replace the Link To with a history.push, including the following parameter, like so: <TableCell style={{width: '10%'}}> <Link to={`/run-id/${item.run_ ...

Using Vue Formulate to effortlessly upload multiple images

One of my projects involves using a Vue Formulate component for uploading multiple images to an Express.js backend. Here is the code snippet for the Vue Formulate component: <FormulateInput type="image" name="property_ ...

Passing props to a wrapped component when utilizing a higher order component in React

While exploring the react documentation, I came across a section on Higher-Order Components that included an example of logging props for a specific component. function logProps(WrappedComponent) { return class extends React.Component { componentWillR ...

Issue TS7053 occurs when trying to access any index of the target of a React.FormEvent<HTMLFormElement>

I've been working on adapting this tutorial to React and TypeScript. Here is the code snippet I have implemented for handling the onSubmit event: const handleSignUp = (event: React.FormEvent<HTMLFormElement>) => { event.preventDefault(); ...

Utilizing d3.js to implement a scatterplot with zoom functionality that focuses solely on zooming the axis without affecting

Having trouble creating a scatterplot with zoom functionality where only the axis is getting zoomed, not the data itself. Can anyone provide some assistance or insight on what might be wrong? If you're interested in checking out the project, here&apo ...

What are effective solutions to reduce the increasing Next.js bundle size caused by dynamic component lookup?

tldr: For more information, please visit the repository. The common.js file includes all dependencies, even though only one is used on the current page. http://localhost:3000/components/ComponentOne http://localhost:3000/components/ComponentTwo Live dem ...

Embedding a CSS file into a PHP class

I've encountered a little issue that I can't seem to solve on my own. I've put together a "webengine" using multiple classes. The primary class responsible for obtaining a theme's internals is called "Logic". This Logic class contain ...