• Sign in to Neowin Faster!

    Create an account on Neowin to contribute and support the site.

  • 0
Sign in to follow this  

[PHP] Simple order form help?

Question

Curve    0

So I have a form with various items in it:

Name | QTY 
Item1 | 3 
Item2 | 2 
Item3 | 1

When I try to insert that data into a MYSQL database its only sending the last item on the list.

I then pass that data to a php file:

 

<?php


function Connect()
{
 $dbhost = "";
 $dbuser = "";
 $dbpass = "";
 $dbname = "";

 // Create connection
 $conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname) or die($conn->connect_error);

 return $conn;
}

?>
<?php

require 'connection.php';
$conn    = Connect();

$item    = $conn->real_escape_string($_POST['u_item']);
$qty    = $conn->real_escape_string($_POST['u_qty']);

$query   = "INSERT into tb_form (name,qty) VALUES('" . $item . "','" . $qty . "')";


$success = $conn->query($query);

if (!$success) {
    die("Couldn't enter data: ".$conn->error);

}

echo "Order Placed";

$conn->close();

?>

 

So I need to add either add an array, loop or individually insert all the fields.

Right now the form to begin with is all just named "item" with distinct values.

 

I'm really confused as to what I'm doing wrong.

 

Could any one give me an example of some functioning code to make this happen?

Share this post


Link to post
Share on other sites

2 answers to this question

Recommended Posts

  • 0
+Fahim S.    1,093

I assume the item fields and quantity fields are all named item and quantity respectively.  Instead you should name them item[] and quantity[].

 

On the server side (php) you can iterate through the array that you get (using a loop) and run a SQL statement for each one of them.

 

You are better off using prepared statements instead of concocting a SQL statement by joining some strings.

 

 

  • Like 1

Share this post


Link to post
Share on other sites
  • 0
+Human.Online    8,692
13 minutes ago, Fahim S. said:

You are better off using prepared statements instead of concocting a SQL statement by joining some strings.

THIS.  So much of this!

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.