Currently, I am expanding my knowledge of PHP and MySQL by working on a dynamic form that utilizes arrays. As I progress through the project,

One of my recent projects involved creating dynamic rows in a form using code. I managed to save the data in an array and display it using a foreach loop, but I'm facing challenges when trying to insert this data into a database.

Here's a glimpse of my UI design:

<div class="form-group">
    <label for="eventname"> Income : </label> 
    <INPUT type="button" value="Add Row" onclick="addRow('dataTable')" class="btn btn-info">
    <INPUT type="button" value="Delete Row" onclick="deleteRow('dataTable')" class="btn btn-info">
    <TABLE id="dataTable" width="350px" border="1">
      <TR>
      <TD><INPUT type="checkbox" name="incomechk[]" class="form-control"></TD>
      <TD>
      <SELECT name="incometype[]" class="form-control">
      <OPTION value="emergency">Emergency Fund</OPTION>
      <OPTION value="investments">Investments</OPTION>
      <OPTION value="retirements">Retirements</OPTION>
      <OPTION value="salary">Salary</OPTION>
      <OPTION value="other">Other</OPTION>
      </SELECT>   
      </TD>
      <TD><INPUT type="number" name="incomevalues[]" class="form-control"></TD>
      </TR>
    </TABLE>
    </div>
    <div class="form-group">
    <label for="Description">Expenses : </label>
    <INPUT type="button" value="Add Row" onclick="addRow('annualTable')" class="btn btn-info">
    <INPUT type="button" value="Delete Row" onclick="deleteRow('annualTable')" class="btn btn-info">
    <TABLE id="annualTable" width="350px" border="1">
      <TR>
      <TD><INPUT type="checkbox" name="expensechk[]"  class="form-control"></TD>
      <TD>
      <SELECT name="expensetype[]" class="form-control">
      <OPTION value="food">Food</OPTION>
      <OPTION value="clothing">Clothing and Accessories</OPTION>
      <OPTION value="shelter">Shelter</OPTION>
      <OPTION value="household">Household</OPTION>
      <OPTION value="tranport">Transportation</OPTION>
      <OPTION value="health">Health</OPTION>
      <OPTION value="loans">Loans</OPTION>
      <OPTION value="miscellaneous">Miscellaneous</OPTION>
      <OPTION value="tuition">Tuition</OPTION>
      <OPTION value="taxes">Taxes</OPTION>
      <OPTION value="vacation">Vacation</OPTION>
      <OPTION value="other">Other</OPTION>
      </SELECT>
      </TD>
      <TD><INPUT type="number" name="expensevalues[]" class="form-control"></TD>
      </TR>
    </TABLE>
    </div>
    <button type="submit" class="btn btn-info" name="submit">SUBMIT</button>
  </form>

In my budgettest.php file, here is a snippet of the functionality I've been working on:

if($bauth['USER'] === $curuser) {
//Income Extraction
$date = $_POST['date'];
$in1 = $_POST['incometype'];
$in2 = $_POST['incomevalues'];
//echo "Incomes : <br/>";
foreach($in1 as $v => $vv){
    echo "into the for loop<br/>";

    $sql1 = "INSERT INTO $curuser (USER,BDATE,BTYPE,BVALUE) VALUES ('$curuser','$date','$in1[$v]','$in2[$v]')";
    $sql2 = mysqli_query($conn,$sql1);
    if($conn->query($sql1)===TRUE) {
        echo "successfully added into $curuser<br/>";
    }
    else {
        echo "not added to database<br/>";
    }
    echo "$in1[$v] "."-"." $in2[$v]";
    echo "<br/>";

}

//Expense Extraction
$exp1 = $_POST['expensetype'];
$exp2 = $_POST['expensevalues'];
//echo "Expenses : <br/>";
foreach($exp1 as $e => $ee){
    $sql2 = "INSERT INTO $curuser (USER,BDATE,BTYPE,BVALUE) VALUES ('$curuser','$date','$exp1[$e]','$exp2[$e]')";
    if($conn->query($sql2) === TRUE) {
        echo "successfully added into $curuser<br/>";
    }
    else {
        echo "not added to database<br/>";
    }

    //echo "$exp1[$e] "."-"." $exp2[$e]";
    //echo "<br/>";
}
}
}

Answer №1

You've run the query twice and using $sql2 isn't actually a query.

$sql1 = "INSERT INTO $curuser 
                (USER,BDATE,BTYPE,BVALUE) 
            VALUES ('$curuser','$date','$in1[$v]','$in2[$v]')";

$sql2 = mysqli_query($conn,$sql1);
if($conn->query($sql1)===TRUE) {

Instead, try:

$sql2 = mysqli_query($conn,$sql1);
if($sql2 === TRUE) {

IMPORTANT

Your code is vulnerable to SQL Injection Attacks. Even if you escape inputs, it's still not secure! Utilize prepared parameterized statements in either the MYSQLI_ or PDO APIs.

Utilizing prepared and parametised queries:

$sql1 = "INSERT INTO $curuser 
                (USER,BDATE,BTYPE,BVALUE) 
            VALUES (?,?,?,?)";

$stmt = $con->prepare($sql1);

// Assuming all params are strings ??
$stmt->bind_values('ssss', $curuser,$date,
                           $in1[$v],$in2[$v]);

$res = $stmt->execute();
if ( !$res ) {
    // query failed
    echo error_log( $con->error );
}else {
    // query success
}

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

Guide on how to validate react-multiselect with the use of Yup validation schema

If the multiselect field is empty, the validation message 'Product is required' is not being displayed. How can I validate this field? Here is the validation schema: validationSchema={ Yup.object().shape({ productID: Yup.string().requi ...

How can we go about looping through each row in the COMMENTS table, querying the REPLIES TABLE for each row, and then adding each result to the corresponding

Looking to dynamically load data with an AJAX request. Comments are being queried successfully, but struggling with querying the replies table for each comment. Trying to put a query inside the div so that it queries REPLIES corresponding to each COMMENT a ...

Comparing the impact of class and element selectors on CSS performance

Considering that CSS is read from right to left, I am pondering the balance between performance and readability when it comes to adding classes to HTML in order to more efficiently target elements in CSS. Additionally, I am curious about how using a gener ...

Utilizing EventEmitters for cascading operations in Angular 2 dropdown menus

I have a form with several cascading drop-downs - the selection in one drop-down determines the options available in the next. Each drop-down retrieves its values from an async data service, and Angular EventEmitter is used to handle events and populate su ...

Using Express.js with Pug.js, dynamically render the page with new content following a fetch POST request

I have a collection of article previews sourced from a database and rendered on the webpage using a Pug.js mixin. each article in articles +articlePreview(article.title, article.text, article.imgSrc) To enhance the user experience, I want to implem ...

Struggling to navigate the world of JavaScript and find the sum of odd numbers?

Currently facing a roadblock with a codewars exercise and in need of some assistance. The exercise involves finding the row sums of a triangle consisting of consecutive odd numbers: 1 3 5 7 9 11 13 15 17 ...

How to trigger an Angular (ionic) view update following an HTTP post request

Is there a way to update the expression in my view after making an HTTP post request? I have tried using the $scope.$apply function, but it gives me an error from ionic.bundle.js saying "$digest already in progress". Could this be a mistake on my part or ...

Getting PHP Post data into a jQuery ajax request can be achieved by using the `$_POST

I'm struggling to figure out how to pass the blog title into the data field of my ajax call. I've been searching for beginner tutorials on SQL, PHP, and AJAX, but haven't found anything that clarifies this issue. If anyone knows of any usefu ...

Experiencing an inexplicable blurring effect on the modal window

Introduction - I've implemented a feature where multiple modal windows can be opened on top of each other and closed sequentially. Recently, I added a blur effect that makes the background go blurry when a modal window is open. Subsequently opening an ...

Contrasts between the storage of data in a static function versus a static object

Trying to figure out the best way to reset a react class component back to its initial state, I came across two different implementations. In my own version, I created an object with initial values and set the component's state equal to it: // My imp ...

Zoom out the slider when scrolling

Take a look at this link and as you scroll down the page, notice how the image transitions to iPhone. Can anyone provide insight on how this effect is achieved? ...

Babel Compile disrupts the flow of commands

I'm facing an issue while attempting to launch my development server after Babel successfully compiles my files. However, the command chain seems to halt right after Babel displays the compilation success message. Babel has completed compiling 82 f ...

Updating or deleting query strings using JavaScript

My URL is structured as follows: http://127.0.0.1:8000/dashboard/post?page=2&order=title I am seeking a way to eliminate the query string ?page={number} or &page={number} Due to my limited knowledge of regular expressions, I am wondering if there ...

Jquery validation is ineffective when it fails to validate

I have implemented real-time jQuery validation for names. It functions correctly in real-time, however, when I attempt to submit the form, it still submits the value even after displaying an error message. Below is the code snippet for the validation: $ ...

When the json string contains more bytes than visible characters, the json_decode() function may encounter errors

It seems like there's an issue with this code snippet: $jsonDecode = json_decode($jsonData, TRUE); Surprisingly, when I manually place the string from $jsonData inside the decode function, it works perfectly fine. This solution does work: $jsonDecod ...

Encountering the error `ReferenceError: document is not defined` when trying to deploy a Next.js project on Vercel

I recently worked on a Next JS project and deployed it to Vercel. Initially, everything was running smoothly, so I didn't check the website status for a while. I was just developing it locally and pushing updates to GitHub. However, when I finally rev ...

Organize the table data based on time

My website specializes in offering cell phone rental services. Users can visit the site to view the available devices that we have. I designed the display of these devices using a table format and components from "@mui/material". One of the columns in thi ...

Redirect in PHP based on the user's computer device

Could PHP be used to identify the user's machine and redirect them to another page if their computer is unauthorized to access the website? This feature is required for creating a "coming soon" page. I only want people I trust to have access, and I ...

CSS and jQuery UI URLs are not resolving properly in MVC framework after deployment

Basically, the issue is that the url for an image in jquery-ui.css file does not resolve once the site is deployed. The website is deployed under the default web site in IIS7, causing the browser console to look for the image in a different location than e ...

Add the AJAX response to the dropdown menu options

Currently in my project, I am utilizing Laravel as a backend. The scenario is such that once the corresponding page loads, it triggers an ajax request to fetch vehicle data which consists of vehicle model and plate number properties. My aim is to display t ...