Script posts the first number in value - php

I am trying to post data to my database. When I post the data I can see that the first number of the value is posted to the database:
Example:
I want to post the value 15. The script posts 1.
I want to post the value 550. The script posts 5.
I want to post the value 30. The script posts 3.
Does someone know the reason for that?
Here is my script:
<input type="text" id="quantity" name="quantity" value="15" />
<input type="text" id="name" name="name" value="550" />
<input type="text" id="price" name="price" value="30" />
<?php
for($count=0; $count<$_POST["total_item"]; $count++)
{
$db3 = new PDO('mysql:host=localhost;dbname=db', 'root', 'pass');
$query3= "INSERT INTO scu_test(id, quantity, name, price) VALUES (:id, :quantity, :name, :price)";
$stmt3 = $db3->prepare($query3);
$exec3 = $stmt3->execute(array(
':id' => $_SESSION['id'],
':quantity' => $_POST["quantity"][$count],
':name' => $_POST["name"][$count],
':price' => $_POST["price"][$count]
));
if($exec3)
{
header('Location: ../succ.php');
}
}
?>
Update 1:
With the answer of Justinas I build the following script:
Dynamic rows:
<input type="text" id="quantity1" name="quantity" value="15" />
<input type="text" id="name1" name="name" value="550" />
<input type="text" id="price1" name="price" value="30" />
<input type="text" id="quantity2" name="quantity" value="15" />
<input type="text" id="name2" name="name" value="550" />
<input type="text" id="price2" name="price" value="30" />
Post:
<?php
foreach($_POST as $i => $item)
{
$db3 = new PDO('mysql:host=localhost;dbname=db', 'root', 'pass');
$query3= "INSERT INTO scu_test(id, quantity, name, price) VALUES (:id, :quantity, :name, :price)";
$stmt3 = $db3->prepare($query3);
$exec3 = $stmt3->execute(array(
':id' => $_SESSION['id'] . '_' . $i,
':quantity' => $_POST["quantity"],
':name' => $_POST["name"],
':price' => $_POST["price"]
));
if($exec3)
{
header('Location: ../succ.php');
}
}
?>
When I post the data to the database I get 18 rows in the database. The data that is posted looks like random data with has no relation with the values in quantity, name or price.
Does someone know what is wrong with the script?

To answer your first issue, the reason that you were only getting the first character of each field value is because you were trying to access the values as if they were arrays, but they were strings -- when you ask for [0] from a string, you will receive the character at the first "offset" aka the first character.
Furthermore, because you had your header() line inside your foreach() loop, you were never going to process more than one set of data before the redirect was executed. The redirect must go outside the loop to prevent causing an early exit.
As for prepared statements, the beauty of prepared statements is that you write the query only once and merely update the bound variables for subsequent executions. In the same vein, you should only create one database connection and keep using it in your script.
Now, as a matter of personal preference, you can choose to write one INSERT query with the entire batch of data or you can conduct several single-row INSERT queries.
As for your question update, you have created unique id values, but duplicated name values for your <input> tags. This means that when the form is submitted, you will not have all of the values in your $_POST array, you will have the "last iterated" set of data. The POST superglobal array is generated using the name values as keys and duplicates keys are not permitted on the same level of an array. So you will have something like this:
$_POST = ["quantity" => "15", "name" => "550", "price" => "30"];
The best advice I can give is to fix your html form. If you don't care about the number associated with each set of fields, use this syntax:
<input type="text" name="quantity[]" value="15" />
<input type="text" name="name[]" value="550" />
<input type="text" name="price[]" value="30" />
With empty square brackets in the name value, php will apply indexed keys while generating a multi-dimensional POST array.
$_POST = [
0 => ["quantity" => "15", "name" => "550", "price" => "30"]
];
If you want to have complete control over the numeric key generated for POST, then write whatever number you wish into the square brackets.
<input type="text" name="quantity[1]" value="15" />
<input type="text" name="name[1]" value="550" />
<input type="text" name="price[1]" value="30" />
<input type="text" name="quantity[4]" value="6" />
<input type="text" name="name[4]" value="577" />
<input type="text" name="price[4]" value="39" />
This generates:
$_POST = [
1 => ["quantity" => "15", "name" => "550", "price" => "30"],
4 => ["quantity" => "6", "name" => "577", "price" => "39"]
];
As for the querying, here is a fully tested demo snippet:
session_start();
$_SESSION['id'] = 44;
$_POST = [
1 => ['quantity' => '15', 'name' => '550', 'price' => '30'],
4 => ['quantity' => '16', 'name' => '551', 'price' => '30']
];
try {
$db = new PDO("mysql:host=localhost;dbname=db;charset=utf8", "root", "");
$stmt = $db->prepare("INSERT INTO scu_test (id, quantity, name, price) VALUES (:id, :quantity, :name, :price)");
foreach ($_POST as $key => $set) {
$exec = $stmt->execute([
':id' => "{$_SESSION['id']}_$key",
':quantity' => $set["quantity"],
':name' => $set["name"],
':price' => $set["price"]
]);
}
header('Location: ../succ.php'); // if error-free, then all successful; redirect
} catch(PDOException $e){
echo "Error message: " , $e->getMessage(); // do not show error messages to users when you go live
}
Inserted Data:
id | quantity | name | price
------|------------|--------|---------
44_1 | 15 | 550 | 30
44_4 | 16 | 551 | 30

It's because your posted data is not multi-dimensional array, but single array:
['quantity' => '', 'name' => '', 'price' => '']
How to fix it:
Add [#] to your HTML:
<div class="item">
<input type="text" class="quantity" name="[0]quantity" value="15" />
<input type="text" class="name" name="[0]name" value="550" />
<input type="text" class="price" name="[0]price" value="30" />
</div>
....
<div class="item">
<input type="text" class="quantity" name="[10]quantity" value="15" />
<input type="text" class="name" name="[10]name" value="550" />
<input type="text" class="price" name="[10]price" value="30" />
</div>
Then in PHP use foreach:
$db3 = new PDO('mysql:host=localhost;dbname=db', 'root', 'pass');
$query3 = "INSERT INTO scu_test(id, quantity, name, price) VALUES (:id, :quantity, :name, :price)";
foreach($items as $i => $item) {
$stmt3 = $db3->prepare($query3);
$result2 = mysqli_fetch_assoc($res2);
$exec3 = $stmt3->execute(array(
':id' => $_SESSION['id'] . '_' . $i, // Don't know why not using Auto-Increment field
':quantity' => $item["quantity"],
':name' => $item["name"],
':price' => $item["price"]
));
if(!$exec3) {
header('Location: ../error.php');
}
}
header('Location: ../succ.php');

Try this
<input type="text" id="quantity1" name="quantity[]" value="15" />
<input type="text" id="name1" name="name[]" value="550" />
<input type="text" id="price1" name="price[]" value="30" />
<input type="text" id="quantity2" name="quantity[]" value="15" />
<input type="text" id="name2" name="name[]" value="550" />
<input type="text" id="price2" name="price[]" value="30" />
your php:
foreach($_POST['quantity'] as $i => $item)
{
$db3 = new PDO('mysql:host=localhost;dbname=db', 'root', 'pass');
$query3= "INSERT INTO scu_test(id, quantity, name, price) VALUES (:id, :quantity, :name, :price)";
$stmt3 = $db3->prepare($query3);
$exec3 = $stmt3->execute(array(
':id' => $_SESSION['id'] . '_' . $i,
':quantity' => $_POST["quantity"][$i],
':name' => $_POST["name"][$i],
':price' => $_POST["price"][$i]
));
if($exec3)
{
header('Location: ../succ.php');
}
}

You should use array in name when using multiple possibilities
<input type="text" id="quantity1" name="quantity[]" value="15" />
<input type="text" id="name1" name="name[]" value="550" />
<input type="text" id="price1" name="price[]" value="30" />
<input type="text" id="quantity2" name="quantity[]" value="15" />
<input type="text" id="name2" name="name[]" value="550" />
<input type="text" id="price2" name="price[]" value="30" />
And in your php script you dont need to append $i in your $_SESSION['id'] just make it primary key and set auto increment in database and do not include it in query it will automatically incremented in each insertion:
<?php
foreach($_POST['quantity'] as $i => $item)
{
$db3 = new PDO('mysql:host=localhost;dbname=db', 'root', 'pass');
$query3= "INSERT INTO scu_test(quantity, name, price) VALUES (:quantity, :name, :price)";
$stmt3 = $db3->prepare($query3);
$exec3 = $stmt3->execute(array(
':quantity' => $_POST["quantity"][$i],
':name' => $_POST["name"][$i],
':price' => $_POST["price"][$i]
));
if($exec3)
{
header('Location: ../succ.php');
}
}
?>
This should insert values as they are if the problem still persists check the length in your database for column quantity, name and price. You need to set int(11) for column quantity, name and price if you want to store integer values and if you want to store alphanumeric values than it should be varchar(250)

Related

PHP inserting multiple checkbox AND textbox arrays into MySQL Database

I'm having trouble with the array results in my php. My first problem is this :
It shows everything even if the checkbox isn't checked. My second problem is that it won't insert the values to the database even though it's connected to the database (as you can see in the previous screenshot, it says "connected successfully").
This is my html form:
<form method="POST">
<input type="hidden" name="item[]" value="cupcake">
<input type="text" name="items" value="cupcake" readonly><br>
<b>Price :</b> <span name="price" value="3.00">$17.00</span><br>
Quantity: <input tabindex="1" name="quantity[]" min="0" max="5" type="number" class="quantity" value="1" /><br>
<input tabindex="1" name="checkbox[]" type="checkbox" value="17" /><span>Add to Cart</span></label></div></div></td><br>
<input type="hidden" name="item[]" value="cake">
<input type="text" name="items" value="cake" readonly><br>
<b>Price :</b> <span name="price" value="20.00">$20.00</span><br>
Quantity: <input tabindex="1" name="quantity[]" min="0" max="5" type="number" class="quantity" value="1" /><br>
<input tabindex="1" name="checkbox[]" type="checkbox" value="20" /><span>Add to Cart</span></label></div></div></td><br>
<input type="submit" name="insertBT"><br>
</form>
PHP:
if(isset($_POST['insertBT']))
{
class db_conn
{
public function create_conn($servername, $username, $password, $db)
{
global $conn;
$conn = new mysqli ($servername, $username, $password, $db);
}
public function check_conn()
{
global $conn;
if($conn->connect_error)
{
die ("Connection Failed : " . $conn->connect_error);
}
else
{
echo ("Connected Successfully <br>");
}
}
public function insert()
{
if(isset($_POST['checkbox'])) {
foreach($_POST['checkbox'] as $check) {
$check = implode(',', $_POST['checkbox']);
$name = implode(',', $_POST['item']);
$quantity = implode(',', $_POST['quantity']);
}
echo $check . "<br>";
echo $name . "<br>";
echo $quantity . "<br>";
mysql_query("INSERT INTO purchases(Product, Quantity, Price) VALUES('$name', '$quantity','$check')");
}
}
}
$obj1 = new db_conn;
$obj1->create_conn("localhost","root","", "dbtest");
$obj1->check_conn();
$obj1->insert();
}
You shouldn't be using implode. That puts a comma-separated list of everything in the form into each row that you insert, and repeats this for every box that's checked. You should just insert one item in each row, by indexing the arrays.
However, when you have a checkbox in a form, it only submits the ones that are checked. The result of this is that the indexes of the $_POST['checkbox'] array won't match up with the corresponding $_POST['item'] and $_POST['quantity'] elements. You need to put explicit indexes into the checkbox names so you can relate them.
<form method = "POST">
<input type = "hidden" name = "item[]" value = "cupcake">
<input type = "text" name = "items" value = "cupcake" readonly><br>
<b>Price :</b> <span name = "price" value = "3.00">$17.00</span><br>
Quantity: <input tabindex="1" name="quantity[]" min="0" max="5" type="number" class="quantity" value="1" /><br>
<input tabindex="1" name="checkbox[0]" type="checkbox" value="17" /><span>Add to Cart</span></label></div></div></td><br>
<input type = "hidden" name = "item[]" value = "cake">
<input type = "text" name = "items" value = "cake" readonly><br>
<b>Price :</b> <span name = "price" value = "20.00">$20.00</span><br>
Quantity: <input tabindex="1" name="quantity[]" min="0" max="5" type="number" class="quantity" value="1" /><br>
<input tabindex="1" name="checkbox[1]" type="checkbox" value="20" /><span>Add to Cart</span></label></div></div></td><br>
<input type = "submit" name = "insertBT"><br>
</form>
Then your PHP code can be like this:
$stmt = $conn->prepare("INSERT INTO purchases (Product, Quantity, Price) VALUES (?, ?, ?)");
$stmt->bind_param("sis", $name, $quantity, $price);
foreach ($_POST['checkbox'] as $i => $price) {
$name = $_POST['name'][$i];
$quantity = $_POST['quantity'][$i];
$stmt->execute();
}
BTW, putting the prices in your HTML seems like a bad idea. Nothing stops the user from modifying HTML using the web inspector before they submit the form, so they could lower the price. You should get the prices from the database when processing the form.
Also, notice that in your original code you opened the database connection using MySQLi, but then you tried to do the insert using mysql_query instead of $conn->query(). You can't mix APIs like that; myql_query can only be used when you open the connection with mysql_connect.

Inserting an array into a relational table

I have 3 tables:
user_login
doc_list
user_cat_link_table
So I am creating a new user and apart of the form shows an array of the available categories which are pulled from the cat_list table.
I am struggling to along with the other form data update the user_cat_link_table.
The script to take the ID of the new user and take the ID of the category selected from the checkboxes array:
Here is my input form:
<form action="actions/add_emp.php" method="post">
<input type="text" name="user" placeholder="Username" required="required" /><br/>
<input type="text" name="pass" type="password" placeholder="Password"/></label><br/>
<input type="text" name="firstname" id="name" required="required"
placeholder="Firstname"/><br />
<input type="text" name="lastname" id="email" required="required"
placeholder="Lastname"/><br/>
<input type="email" name="email" id="city" required="required"
placeholder="Email Address"/><br/>
<input type="text" name="extension" id="extension" required="required"
placeholder="Extension Number"/><br/>
<select name="title">
<option selected disabled>Please Select a Job Title...</option>
<option disabled></option>
<option disabled>Helpesk:</option>
<option value="Technical Support Advisor">Technical Support Advisor</option>
<option value="Deputy Team Leade">Deputy Team Leader</option>
<option value="Team Leader">Team Leader</option>
<option value="Incident Resolution Advisor">Incident Resolution Advisor
</option>
<option disabled></option>
<option disabled>Call Centre:</option>
<option value="Technical Support Advisor">Technical Support Advisor</option>
<option value="">Deputy Team Leader</option>
<option value="">Team Leader</option>
<option disabled></option>
</select>
<div id="checkboxlist" >
<?php
foreach($category as $cat){
?>
<input type="checkbox" value="<?php echo $cat["cat_id"]; ?>"
name="cat_no[]" id="box1"> <?php echo $cat["cat_title"]; ?></a><br>
<?php
}
?>
</div>
<input type="submit" value="Add User" name="submit"/><br />
</form>
I can see if I do a print_r() or var_dump() I am getting the results I expect:
Array ( [action] => id
[user] => test23wer3e4weret4essd
[pass] => test [firstname] => test
[lastname] => test
[email] => tes#test.com
[extension] => 1234
[cat_no] => Array ( [0] => 69
[1] => 70
[2] => 71 )
[submit] => Add User )
Here is the form which acts as the script to insert the data into both the user_login table (which works) but its the part at the bottom trying to insert into the join table I am having trouble with:
<?
session_start();
session_regenerate_id();
if(!ini_get('date.timezone'))
{
date_default_timezone_set('GMT');
}
if(isset($_POST["action"])){
if(isset($_POST['submit'])){
include_once'../../config.php';
$dbh = new PDO("mysql:host=$hostname;dbname=dashboardr",$username,$password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(isset($_POST['user']) && isset($_POST['pass'])){
$password=$_POST['pass'];
$sql=$dbh->prepare("SELECT COUNT(*) FROM `user_login` WHERE `username`=?");
$sql->execute(array($_POST['user']));
if($sql->fetchColumn()!=0){
die("User Exists");
}else{
function rand_string($length) {
$str="";
$chars = "subinsblogabcdefghijklmanopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$size = strlen($chars);
for($i = 0;$i < $length;$i++) {
$str .= $chars[rand(0,$size-1)];
}
return $str;
}
$p_salt = rand_string(20);
$site_salt="subinsblogsalt";
$salted_hash = hash('sha256', $password.$site_salt.$p_salt);
$sql=$dbh->prepare("INSERT INTO `user_login`
(`id`, `username`, `password`, `psalt`,
`firstname`, `lastname`, `email`, `extension`)
VALUES (NULL, ?, ?, ?, ?, ?, ?, ?)");
$sql->execute(
array($_POST['user'], $salted_hash, $p_salt, $_POST["firstname"],
$_POST["lastname"], $_POST["email"], $_POST["extension"]));
print_r($_POST);
die();
$docId = $dbh->lastInsertId();
$sql = "INSERT INTO `user_cat_link_table`(`UserID`, `Cat_ID`) VALUES";
$values = "";
$params = [];
foreach($_POST["cat_no"] as $cat)
{
$values.= "(?, ?), ";
$params[] = $cat; // correct here
$params[] = $docId;
}
$values = substr($values, 0, -2);
$sql.= $values;
$query = $dbh->prepare($sql);
$query->execute($params);
if ($dbh->query($sql)) {
}else{}
$dbh = null;
} //catch(PDOException $e)
header ('Location: ../list_doc.php?success=1');
}
}
}
?>

Save Dynamic Array To MySQL Database

I have a dynamic form that allows users to enter information and that form can be submitted multiple times and the page will show all of the inputted data thanks to $_SESSION. That information is sent to another page where it will be saved to a MySQL database after submission.
I can't get it to save all of the information. If I have 3 groups of data, it will only write the last one into the database. How do I save the entire array to the database?
This is the page that shows all of the dynamic information:
<?php
$invoice_no = $_SESSION['invoice'];
if(isset($_SESSION['order'])) :
foreach($_SESSION['order'] as $sav) {
?>
<form action="addrow.php" method="post">
<label>Length</label><input type="text" name="length" value="<?php echo $sav['length']; ?>" size="2">
<label>Width</label><input type="text" name="width" value="<?php echo $sav['width']; ?>" size="2">
<label>Color</label><input type="text" name="color" value="<?php echo $sav['color']; ?>" size="4">
<label>Quantity</label><input type="text" name="quantity" value="<?php echo $sav['quantity']; ?>" size="2">
<label>Invoice Is Hidden</label><input type="hidden" name="invoice" value="<?php echo $invoice_no; ?>">
<input type="hidden" name="total" value="<?php echo $sav['total']; ?>" />
<input type="hidden" name="PaymentStatus" value="PAID">
<br>
<?php } endif; ?>
<br><br>
<input type="submit" value="Submit" name="upload">
</form>
This page saves it to the database. I was unsure of how to save the array into the database, so I used the same code to show the session data and I modified it but failed:
<?php
require("addrow_info.php");
if(isset($_POST['upload'])) :
$decal = array(
'length' => $_POST['length'],
'width' => $_POST['width'],
'color' => $_POST['color'],
'quantity' => $_POST['quantity'],
'total' => $_POST['total'],
'invoice' => $_POST['invoice'],
'paymentStatus' => $_POST['PaymentStatus'],
'submit' => $_POST['upload']
);
$_POST['order'][] = $decal;
endif;
if(isset($_POST['order'])) :
foreach($_POST['order'] as $newOrder) {
// Opens a connection to a MySQL server
$connection=mysql_connect ("localhost", $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
// Insert new row with user data
$query = "INSERT INTO orders (PaymentStatus, invoice_no, length, width, color, quantity, total ) VALUES ('".$newOrder['paymentStatus']."','".$newOrder['invoice']."','".$newOrder['length']."', '".$newOrder['width']."', '".$newOrder['color']."', '".$newOrder['quantity']."', '".$newOrder['total']."')";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
echo "$query";
mysql_close();
}
} endif;
header ("location:/thankyou.php");
?>
I was reading about using the serialize() function but I'm not sure if that's best for what I'm trying to accomplish. I want each group of data to save in one row under their respective column.
It should look like this:
Length Width Color Invoice Quantity Total PaymentStatus
5 5 Green abc123 1 2.00 PAID <--Each row is a group
6 6 blue def234 2 3.00 PAID
What is the best solution for saving an array into a MySQL database?
<form action="addrow.php" method="post"><?php
$invoice_no = $_SESSION['invoice'];
if(isset($_SESSION['order'])) :
foreach($_SESSION['order'] as $sav) {
?>
<label>Length</label><input type="text" name="length[]" value="<?php echo $sav['length']; ?>" size="2">
<label>Width</label><input type="text" name="width[]" value="<?php echo $sav['width']; ?>" size="2">
<label>Color</label><input type="text" name="color[]" value="<?php echo $sav['color']; ?>" size="4">
<label>Quantity</label><input type="text" name="quantity[]" value="<?php echo $sav['quantity']; ?>" size="2">
<label>Invoice Is Hidden</label><input type="hidden" name="invoice[]" value="<?php echo $invoice_no; ?>">
<input type="hidden" name="total[]" value="<?php echo $sav['total']; ?>" />
<input type="hidden" name="PaymentStatus" value="PAID">
<br>
<?php } endif; ?>
<br><br><input type="submit" value="Submit" name="upload">
</form>
try it and print_r( $_POST ), I think you can make it.
if(isset($_POST['upload'])) {
print_r($_POST);
}
Array ( [length] => Array ( [0] => 2 [1] => 3 [2] => 4 ) [width] => Array ( [0] => 2 [1] => 3 [2] => 3 )
for($i=0;$i<count($_POST['length']);$i++){
$order = array(
'length'=>$_POST['length'][$i],
'width'=>$_POST['width'][$i]),
//...............
);
$sql = "INSERT INTO orders (PaymentStatus, invoice_no, length, width, color, quantity, total ) VALUES ('{$order['paymentStatus']}','{$order['invoice']}','{$order['length']}', '{$order['width']}', '{$order['color']}', '{$order['quantity']}', '{$order['total']}')";
mysql_query($sql);
}

How can I prepare mysqli statement that uses arrays?

Im using the below form
<form method="get" action="daily_process.php">
Horse / Course / Time
<input type='text' name='horse[]' />
<input type="text" name="course[]" />
<input type="text" name="time[]" />
<input type='text' name='horse[]' />
<input type="text" name="course[]" />
<input type="text" name="time[]" />
<input type='text' name='horse[]' />
<input type="text" name="course[]" />
<input type="text" name="time[]" />
<input name="submit" type="submit" />
</form>
Im using the below code to process the form array and output it as print
<?php
$horse = $_POST['horse'];
$course = $_POST['course'];
$time = $_POST['time'];
foreach( $horse as $key => $h ) {
if ($horse[$key] != "") {
print "The horse is ".$h.", course is ".$course[$key].
", and time is ".$time[$key]." Thank you <br/>" ;
}}
?>
my question is how can I prepare these results for mysqli?
I have seen the below example on StackOverflow, but how can I edit it to suit my purpose?
ie. I need to save $horse, $course, and $timeto database -
table (horse,course, time) VALUES (?, ?, ?)
$query = "INSERT INTO table (link) VALUES (?)";
$stmt = $mysqli->prepare($query);
foreach ($array as $one) {
$stmt ->bind_param("s", $one);
$stmt->execute();
}
$stmt->close();
$query = "INSERT INTO table (horse,course,time) VALUES (?,?,?)";
$stmt = $mysqli->prepare($query);
foreach( $horse as $key => $h ) {
$stmt ->bind_param("sss", $h, $course[$key], $time[$key]);
$stmt->execute();
}
Assuming all the values are strings
The examples for bind_param in the PHP docs do show how to bind multiple values.

Insert array values + single form values into all rows

I am trying to insert values from a form into my mysql database. I have single value forms + array values from the form. How can I insert the array values into my database with the single form values attached to all rows?
The HTML:
Start:<br>
<input type="text" name="start" id="start">
End:<br>
<input type="text" name="end" id="end">
<input type="text" name="item[]" placeholder="Manufacturer #" /><br>
<input type="text" name="description[]" placeholder="Description" /><br>
<input type="text" name="item[]" placeholder="Manufacturer #" /><br>
<input type="text" name="description[]" placeholder="Description" /><br>
<input type="text" name="item[]" placeholder="Manufacturer #" /><br>
<input type="text" name="description[]" placeholder="Description" /><br>
The PHP:
if (isset($_POST['submit']))
{
$link = mysql_connect('localhost', 'user', 'pass');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("mydb") or die(mysql_error());
echo 'Connected successfully';
$query = "INSERT INTO agreement (start, end, item_number, item_description) VALUES ";
foreach($_POST['item'] as $i => $item)
{
// Get values from post.
$item = mysql_real_escape_string($item);
$description = mysql_real_escape_string($_POST['description'][$i]);
$start = mysql_real_escape_string($_POST['start'][$i]);
$end = mysql_real_escape_string($_POST['end'][$i]);
// Add to database
$query = $query." ('$start','$end','$item','$description') ,";
}
$query = substr($query,0,-1); //remove last char
$result = mysql_query($query);
}
I will be changing the code to mysqli/pdo, I know that the current code is unsecure.
Any help is appreciated, thanks!
Just use $_POST['start'] and $_POST['end'] without array access since they will be the same each time. You can use array access for item and description.

Categories