I need to be able to update my form data once the submit button is pressed on the same page.
I have a csv file. And at the moment, I have worked out how to edit data inside it, and save it in the csv file (through a form).
-(I have attached the main code below, but even any suggestions would be helpful)
The form and php execution is on the same page, but once the user edits the values and presses submit, the data goes back to the original data. So it updates in the csv file, but not in the form.
This is the form:
for ($i=0; $i<200; $i++) {
if(empty($SearchResults[$i][0]) == false){ //If its full
?>
<form method="post" action="">
Full Name: <input name = "Name2" type="text" value="<?php echo $SearchResults[$i][0] ?>"/>
Weight (kg): <input name="Weight2" type="number" value="<?php echo $SearchResults[$i][1] ?>"/>
Weight of belongings (kg): <input name="WeightOfBelongings2" type="number"value="<?php echo $SearchResults[$i][2] ?>"/>
<input name="submit" type="submit" />
</form>
<?php
$i++;
}else if (empty($SearchResults[$i][0]) == true){ //If it is empty
$i =201;
}
}
This is what happens when the submit button is pressed:
if (isset($_POST['submit'])) {
$FullName = $_POST['Name2'];
$Weight = $_POST['Weight2'];
$WeightOfBelongings = $_POST['WeightOfBelongings2'];
//Creates a new felon from the class in felen.php and assigns it to this variable $Felon
$Felen = new felen;
//This refers to a function in the class Felen. From this information it calculates the costs, ammounts etc. And saves it to a variable that can be called.
$Felen -> CreateFelen($FullName, $Weight, $WeightOfBelongings);
//This is a for loop that checks when there is an avaliable line to put the data into.
if ($FullName != "") {
$i = 0;
for ($i=0; $i<200; $i++) {
if(empty($csv[$i][0]) == false){ //If its full
if($csv[$i][0] == $_POST['Name2']){
//its only printing it if it is in the first row?
$csv[$i][0] = $FullName;
$csv[$i][1] = $Weight;
$csv[$i][2] = $WeightOfBelongings;
$csv[$i][3] = $Felen->FelenTotalWeight;
$csv[$i][4] = $Felen->UnassembliumRequired;
$csv[$i][5] = $Felen->ReassembliumRequired;
$csv[$i][6] = $Felen->CostOfUnassemblium;
$csv[$i][7] = $Felen->CostOfReassemblium;
$csv[$i][8] = $Felen->TotalCostOfJourney;
$i = 201;
}
}
}
//Saves the previous data and new changes to the csv file
//This opens to file as a write file
$fp = fopen('data.csv', 'w');
//This takes the array that has had data ddded to it and adds it to the file
foreach ($csv as $fields) {
fputcsv($fp, $fields);
}
//This closes the file
fclose($fp);
}
}
Thank you very much!
I have some problem with the logic and any help would be appreciated:
$total_add = $_POST['xTotalNumProduct'];
if(ISSET($_SESSION['cart']['CartTotalNum']) && $_SESSION['cart']['CartTotalNum'] > 0) {
$CartTotalNum = $_SESSION['cart']['CartTotalNum'];
$cart = $_SESSION['cart'];
for ($i=1; $i<=$total_add; $i++) {
for ($x=1; $x<=$CartTotalNum; $x++) {
if ($cart['ItemId'.$x] == $_POST['xPdt'.$i.'Id']) { // this will only check the first key ie $cart['ItemId1]
$cart['ItemQty'.$x] = $_POST['xPdt'.$i.'Qty'];
}
else {
$CartTotalNum = $CartTotalNum + 1;
$cart['ItemId'.$CartTotalNum] = $_POST['xPdt'.$i.'Id'];
$cart['ItemQty'.$CartTotalNum] = $_POST['xPdt'.$i.'Qty'];
}
}
}
$cart['CartTotalNum'] = $CartTotalNum;
} else {
$cart = array();
for ($i=1; $i<=$total_add; $i++) {
$cart['ItemId'.$i] = $_POST['xPdt'.$i.'Id'];
$cart['ItemQty'.$i] = $_POST['xPdt'.$i.'Qty'];
}
$cart['CartTotalNum'] = $total_add;
}
The problem with the above script is that it only checks the $cart['ItemId1] and if not equal it will add to cart without checking $cart['ItemId2], $cart['ItemId3] etc.
How can I fix that?
This is incredibly bad code:
$cart['ItemQty'.$x] = $_POST['xPdt'.$i.'Qty'];
^^^^^
Why build dynamic keys? You can use a multi-dimensional arrays quiet easily:
$_SESSION['cart'][$itemID]['quantity'] = $_POST[...];
Keying your cart by the itemID allows all of the item's cart data to be kept in one place, instead of scattered everywhere.
And note that similar constructs can be used in your form field names, e.g.
<input type="text" name="foo[bar][baz][42]" ... >
would give you
$_REQUEST['foo']['bar']['baz'][42]
to work with when the form's submitted.
This question was asked years ago, but for anyone running into it now, this is what worked for me.
I put this HTML in my page:
<form method="post" action="/">
<input type="hidden" name="E24MT1260" value="23">
<input type="hidden" name="ACFIT60060015" value="14">
<input type="hidden" name="programatic_add_to_cart" value="true">
<input type="submit" value="Add to cart">
</form>
And added this to my functions.php
<?php
add_action('wp_loaded', function() {
global $woocommerce;
if (!empty($_POST) && !empty($_POST['programatic_add_to_cart'])){
global $woocommerce;
foreach ($_POST as $sku => $quantity) {
$product_id = wc_get_product_id_by_sku($sku);
$woocommerce->cart->add_to_cart($product_id, $quantity);
}
wp_redirect( '/cart' );
exit;
}
});
?>
I am trying to save the value selected in the date drop down box to a variable '$AvailabilityID' which is retrieved on the next page. The drop down box is populated from the MYSQL table bs_availability. From what I've read I need to use Javascript but really no idea how to do it.
Any help appreciated.
<?php
//current URL of the Page. cart_update.php redirects back to this URL
$current_url = base64_encode("http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
$results = $mysqli->query("SELECT SessionType, SessionName, SessionCost, SessionID FROM bs_session
GROUP BY SessionName ORDER BY SessionType ASC;");
if ($results) {
//output results from database
while($obj = $results->fetch_object())
{
$availabilityresults = $mysqli->query("SELECT * From bs_availability WHERE sessionID = ".$obj->SessionID.";");
echo '<tr>';
echo '<form method="post" action="cart_update.php">';
echo '<td>'.$obj->SessionName.'</td>';
echo '<td>'.$obj->SessionType.'</td>';
echo '<td><select name="date">';
//While loop to populate drop down with table data
while($objdate = $availabilityresults->fetch_object())
{
echo '<option value ="'.$objdate->AvailabilityID.'">'.$objdate->Date.'</option>';
}
echo '</select>';
echo '</td>';
echo '<td>Price '.$currency.$obj->SessionCost.' <button class="add_to_cart">Add To Cart</button></td>';
echo '</tr>';
echo '<input type="hidden" name="SessionID" value="'.$obj->SessionID.'" />';
echo '<input type="hidden" name="AvailabilityID" value="'.$objdate->AvailabilityID.'" />';
echo '<input type="hidden" name="type" value="add" />';
echo '<input type="hidden" name="return_url" value="'.$current_url.'" />';
echo '</form>';
echo '</div>';
}
}
?>
EDIT: This code is the cart_update.php. So when Add to Basket is pressed this script is run using the $SessionID from the selected item but I also need the AvailabiltyID of the chosen date so that I can run the right query to add the right date to the basket.
<?php
session_start(); //start session
include_once("config.php"); //include config file
//empty cart by distroying current session
if(isset($_GET["emptycart"]) && $_GET["emptycart"]==1)
{
$return_url = base64_decode($_GET["return_url"]); //return url
session_destroy();
header('Location:'.$return_url);
}
//add item in shopping cart
if(isset($_POST["type"]) && $_POST["type"]=='add')
{
$SessionID = filter_var($_POST["SessionID"], FILTER_SANITIZE_STRING); //product code
$AvailabilityID = filter_var($_POST["AvailabilityID"], FILTER_SANITIZE_STRING); //product code
$product_qty = filter_var($_POST["product_qty"], FILTER_SANITIZE_NUMBER_INT); //product code
$return_url = base64_decode($_POST["return_url"]); //return url
//limit quantity for single product
if($product_qty > 10){
die('<div align="center">This demo does not allowed more than 10 quantity!<br />Back To Products.</div>');
}
console.log($availabilityID);
//MySqli query - get details of item from db using product code
$results = $mysqli->query("SELECT SessionName, SessionCost FROM bs_session WHERE SessionID=$SessionID LIMIT 1");
//$results = $mysqli->query("SELECT bs_session.SessionName, bs_availability.Date, bs_session.SessionCost FROM bs_availability INNER JOIN bs_session ON bs_session.SessionID=bs_availability.SessionID WHERE bs_availability.AvailabilityID=$AvailabilityID LIMIT 1");
$obj = $results->fetch_object();
if ($results) { //we have the product info
//prepare array for the session variable
$new_product = array(array('name'=>$obj->SessionName, 'code'=>$SessionID, 'date'=>$obj->Date, 'price'=>$obj->SessionCost));
if(isset($_SESSION["products"])) //if we have the session
{
$found = false; //set found item to false
foreach ($_SESSION["products"] as $cart_itm) //loop through session array
{
if($cart_itm["code"] == $SessionID){ //the item exist in array
$product[] = array('name'=>$cart_itm["name"], 'code'=>$cart_itm["code"], 'date'=>$cart_itm["date"], 'price'=>$cart_itm["price"]);
$found = true;
}else{
//item doesn't exist in the list, just retrive old info and prepare array for session var
$product[] = array('name'=>$cart_itm["name"], 'code'=>$cart_itm["code"], 'date'=>$cart_itm["date"], 'price'=>$cart_itm["price"]);
}
}
if($found == false) //we didn't find item in array
{
//add new user item in array
$_SESSION["products"] = array_merge($product, $new_product);
}else{
//found user item in array list, and increased the quantity
$_SESSION["products"] = $product;
}
}else{
//create a new session var if does not exist
$_SESSION["products"] = $new_product;
}
}
//redirect back to original page
header('Location:'.$return_url);
}
//remove item from shopping cart
if(isset($_GET["removep"]) && isset($_GET["return_url"]) && isset($_SESSION["products"]))
{
$SessionID = $_GET["removep"]; //get the product code to remove
$return_url = base64_decode($_GET["return_url"]); //get return url
foreach ($_SESSION["products"] as $cart_itm) //loop through session array var
{
if($cart_itm["code"]!=$SessionID){ //item does,t exist in the list
$product[] = array('name'=>$cart_itm["name"], 'code'=>$cart_itm["code"], 'qty'=>$cart_itm["qty"], 'price'=>$cart_itm["price"]);
}
//create a new product list for cart
$_SESSION["products"] = $product;
}
//redirect back to original page
header('Location:'.$return_url);
}
In PHP, this is done through the POST array on your cart_update.php page:
if (isset($_POST['date'])){
$AvailabilityID = $_POST['date'];
}
You could also change the existing add to cart button to give it a name that will appear in the POST array:
echo '<td>Price '.$currency.$obj->SessionCost.' <button class="add_to_cart" name="add_to_cart">Add To Cart</button></td>';
This is often used as a check on the processing page, with an if block around all of the processing code.
if (isset($_POST['add_to_cart'])){
//all processing code here
}
Just use the POST Variable $_POST['date'] which holds the selected option value.
This question already has answers here:
Best way to INSERT many values in mysqli?
(4 answers)
Closed 2 years ago.
I need to insert entries to mysql table from the form below.
1-form contains many rows.
2-entry will not be always consecutive in the rows (meaning row 1 can be empty and next row not)
3-all rows containing entries should be saved in the db table.
i want to INSERT INTO oz2ts_custompc_details (part_id, quantity, price)
Here is my entry form (custompc_form2.php)
<!DOCTYPE html>
<html>
<body>
<form action="../subs/custompcorder2.php/" method="post" id="form">
<p><input id="name" name="part_id[]"/>
<input type="text" id="quantity" name="quantity[]"/>
<input id="name-data" type="text" name="price[]"/></p>
<p><input id="name" name="part_id[]"/>
<input type="text" id="quantity" name="quantity[]"/>
<input id="name-data" type="text" name="price[]"/></p>
<p><input id="name" name="part_id[]"/>
<input type="text" id="quantity" name="quantity[]"/>
<input id="name-data" type="text" name="price[]"/></p>
<p><input id="name" name="part_id[]"/>
<input type="text" id="quantity" name="quantity[]"/>
<input id="name-data" type="text" name="price[]"/></p>
<input id="submit" type="submit" value="Submit Order" name="submission"/>
</form>
</body>
</html>
here is What I came up with but still not working.
here is the summary of how it is working: ||Rows 1 to 4 has data > all 4 are saved || row 1 is empty and rows 2 to 3 contains data > only rows 2 and 3 are saved not row 4|| Row 2 only has data all other are empty > Data not saved || Rows 2 and 3 has data > Row 2 only is saved
<?php
include '../db/connect.php';
foreach (array('part_id', 'quantity', 'price') as $pos) {
foreach ($_POST[$pos] as $id => $row) {
$_POST[$pos][$id] = mysqli_real_escape_string($con, $row);
}
}
$ids = $_POST['part_id'];
$quantities = $_POST['quantity'];
$prices = $_POST['price'];
$items = array();
$size = count($ids);
for($i = 0 ; $i < $size ; $i++){
// Check for part id
if (empty($ids[$i]) || empty($quantities[$i]) || empty($prices[$i])) {
continue;
}
$items[]=array(
"part_id" => $ids[$i],
"quantity" => $quantities[$i],
"price" => $prices[$i]
);
}
if (!empty($items)) {
$values = array();
foreach($items as $item){
$values[] = "('{$item['part_id']}', '{$item['quantity']}', '{$item['price']}')";
}
$values = implode(", ", $values);
$sql = "INSERT INTO oz2ts_custompc_details (part_id, quantity, price) VALUES {$values} ;
" ;
$result = mysqli_query($con, $sql );
if ($result) {
echo 'Successful inserts: ' . mysqli_affected_rows($con);
} else {
echo 'query failed: ' . mysqli_error($con);
}
}
?>
The first is a simplified entry form. The reel entry form looks like this:
<!DOCTYPE html>
<html>
<head></head>
<body>
<form action="../subs/custompcorder2.php/" method="post" id="form">
<div id="orderwrap">
<div id="orderheather">
<select id="platform" name="platform">
<option selected="selected" disabled="disabled">Select the
platform</option>
<option value="Intel">Intel</option>
<option value="AMD">AMD</option>
</select>
</div>
<div id="orderbody">
<p><select id="part_id" name="part_id[]">
<option selected="selected" disabled="disabled">Choose part1 </option>
<?php query() ?>
< /select>
<input type="text" id="quantity" name="quantity[]"/>
<input id="name-data" type="text" name="price[]"/></p>
<p><select id="part_id" name="part_id[]">
<option selected="selected" disabled="disabled">Choose part2 </option>
<?php query2() ?>
< /select>
<input type="text" id="quantity" name="quantity[]"/>
<input id="name-data" type="text" name="price[]"/></p>
<p><select id="part_id" name="part_id[]">
<option selected="selected" disabled="disabled">Choose part3 </option>
<?php query3() ?>
< /select>
<input type="text" id="quantity" name="quantity[]"/>
<input id="name-data" type="text" name="price[]"/></p>
<p><select id="part_id" name="part_id[]">
<option selected="selected" disabled="disabled">Choose part4 </option>
<?php query4() ?>
< /select>
<input type="text" id="quantity" name="quantity[]"/>
<input id="name-data" type="text" name="price[]"/></p>
<input id="submit" type="submit" value="Submit Order"name="submission"/>
</div>
</div>
</form>
</body>
</html>
Here is the php page containing function query(),query1(),..
<?php
include '../db/connect.php';
function query(){
global $con;
$myData=mysqli_query($con,"SELECT * FROM oz2ts_mijoshop_product");
while($record=mysqli_fetch_array($myData)){
echo'<option value="'.$record['product_id'].'">'.$record['model'].'</option>';
}
}
function query2(){
global $con;
$myData=mysqli_query($con,"SELECT * FROM oz2ts_mijoshop_product");
while($record=mysqli_fetch_array($myData)){
echo'<option value="'.$record['product_id'].'">'.$record['model'].'</option>';
}
}
function query3(){
global $con;
$myData=mysqli_query($con,"SELECT * FROM oz2ts_mijoshop_product");
while($record=mysqli_fetch_array($myData)){
echo'<option value="'.$record['product_id'].'">'.$record['model'].'</option>';
}
}
function query4(){
global $con;
$myData=mysqli_query($con,"SELECT * FROM oz2ts_mijoshop_product");
while($record=mysqli_fetch_array($myData)){
echo'<option value="'.$record['product_id'].'">'.$record['model'].'</option>';
}
}
function close(){
mysqli_close($con);
}
?>
Sanitize input correctly using array_map
Check for input before adding to array
Only run SQL if anything to be added
Use the following code:
<?php
include '../db/connect.php';
foreach (array('part_id', 'quantity', 'price') as $pos) {
foreach ($_POST[$pos] as $id => $row) {
$_POST[$pos][$id] = mysqli_real_escape_string($con, $row);
}
}
$ids = $_POST['part_id'];
$quantities = $_POST['quantity'];
$prices = $_POST['price'];
$items = array();
$size = count($ids);
for($i = 0 ; $i < $size ; $i++){
// Check for part id
if (empty($ids[$i]) || empty($quantities[$i]) || empty($prices[$i])) {
continue;
}
$items[] = array(
"part_id" => $ids[$i],
"quantity" => $quantities[$i],
"price" => $prices[$i]
);
}
if (!empty($items)) {
$values = array();
foreach($items as $item){
$values[] = "('{$item['part_id']}', '{$item['quantity']}', '{$item['price']}')";
}
$values = implode(", ", $values);
$sql = "INSERT INTO oz2ts_custompc_details (part_id, quantity, price) VALUES {$values} ;
" ;
$result = mysqli_query($con, $sql );
if ($result) {
echo 'Successful inserts: ' . mysqli_affected_rows($con);
} else {
echo 'query failed: ' . mysqli_error($con);
}
}
Here is a rough code, modify indeces by your own needs.
$ids = $_POST['part_id'] ;
$quantities = $_POST['quantity'] ;
$prices = $_POST['price'];
$items = array();
$size = count($names);
for($i = 0 ; $i < $size ; $i++){
$items[$i] = array(
"part_id" => $ids[$i],
"quantity" => $quantities[$i],
"price" => $prices[$i]
);
}
$values = array();
foreach($items as $item){
$values[] = "('{$item['part_id']}', '{$item['quantity']}', '{$item['price']}')";
}
$values = implode(", ", $values);
$sql = "
INSERT INTO oz2ts_custompc_details (part_id, quantity, price) VALUES {$values} ;
" ;
Here's an example of basic issue handling while inserting data. Included in error checks are
Confirm that we received all 3 fields - part_id, quantity and price
If there were 3 rows of part_id, there must be 3 rows of quantity and price
Add safety by preparing INSERT statement
Bind variables to the prepared statements
Pick up only those rows in which all 3 fields (part_id, quantity and price) were entered, and that they were valid numbers
Code that receives POST
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
// debug information. Let's find what the page is receiving
echo '<pre>', print_r($_POST, true), '</pre>';
$postedData = $_POST;
// confirm that we received all 3 fields - part_id, quantity, price
$fieldsReceived = true;
if ( !confirmFields('part_id')
|| !confirmFields('quantity')
|| !confirmFields('price')
) {
echo 'part_id, quantity or price has not been received. Exiting.';
exit;
}
// confirm that each of them have identical item-count
if ( count($postedData['part_id']) !== count($postedData['quantity'])
|| count($postedData['part_id']) !== count($postedData['price'])
) {
echo count($postedData['price_id']) .
' fields received for price_id, but different number of fields
were received for quantity or price. Please ensure that part_id,
quantity and price have the same number of fields. Exiting.';
exit;
}
// establish connection using mysqli_connect
$connection = mysqli_connect('localhost', 'user', 'pass', 'selected_db');
// prepare an insert statement
$sql = 'insert into oz2ts_custompc_details
(part_id, quantity, price) values
(?, ?, ?)';
$statement = mysqli_prepare($connection, $sql);
// bind integer, integer, double to the parameters in insert statement
// corresponding to the question marks
$part = 0;
$qty = 0;
$prc = 0.0000;
mysqli_stmt_bind_param($statement, 'iid', $part, $qty, $prc);
// loop through received data and only insert those that have valid values
// in part_id, quantity and price
$partsReceived = count($postedData['part_id']);
for ($i = 0; $i < $partsReceived; $i++) {
// if drop down boxes are used and default value for part is
// Choose part, let's see if user left the selection to default
// and ignore that line
if (strpos($postedData['part_id'][$i], 'Choose part') !== false) {
continue;
}
// do we have numeric data in current line?
// although not done here, one can check if part_id is integer (is_int)
// quantity is_int and price is_float before proceeding further
if ( !is_numeric($postedData['part_id'][$i])
|| !is_numeric($postedData['quantity'][$i])
|| !is_numeric($postedData['price'][$i])
) {
echo '<p>Entry # ' . ($i + 1) . '
will be ignored because of missing
or invalid part_id, quantity, or price</p>';
continue;
}
// update bind parameters
$part = $postedData['part_id'][$i];
$qty = $postedData['quantity'][$i];
$prc = $postedData['price'][$i];
// execute statement and move on to the next one
try {
mysqli_stmt_execute($statement);
echo '<p>Inserted part_id ' . $postedData['part_id'][$i] . '</p>';
} catch (Exception $e) {
echo '<p>Could not enter data with part_id '
. $postedData['part_id'][$i] . '<br>'
. 'Error ' . $e->getMessage() . '</p>';
}
}
// --------------------------
// FUNCTIONS
// --------------------------
/**
* Confirm that we received part_id, quantity and price from POST
*
* #param string $fieldName Name of the field to verify
*
* #return bool True if fieldname is set as an array; False otherwise
*/
function confirmFields($fieldName)
{
global $postedData;
return
(!isset($postedData[$fieldName]))
&& !is_array($postedData[$fieldName]) ? false : true;
}
?>
I am writing a script to place an order which will be added to a cart, I am storing the selected values for the cart as a session. Each new selection (addition to the cart) is added to a new session which is incremented by one each time.
ie.
$_SESSION['cart'][1]
$_SESSION['cart'][2]
$_SESSION['cart'][3]
I am receiving the below error and am stumped.
Warning: Cannot use a scalar value as an array in C:\wamp\www\php\cart\carting\order.php on line 37 -(This is the line $_SESSION['cart'][$p] = $cartstring;)
<?PHP
session_start();
$productlist = $_POST['products']; //Form post
if (isset($productlist)) {
if (!isset($_SESSION['cart'])) {
$p = 0;
$_SESSION['cart'][$p];
print $_SESSION['cart'][$p];
}
elseif (isset($_SESSION['cart'])) {
$p = count($_SESSION['cart']);
$p++;
$product = explode('-', $productlist[1][0]);
$productname = $product[0];
$productprice = $product[1];
$productqty = $productlist[1][1];
$itemsubtotal = ($productprice * $productqty);
$cartstring = "productid-$productname-$productprice-$productqty-$itemsubtotal";
$_SESSION['cart'][$p] = $cartstring; //THIS IS LINE 37
}
}
$product1 = "Bread";
$price1 = 12;
$product2 = "Butter";
$price2 = 2;
print '<form action="order.php" method="post">';
print '<input type="checkbox" name="products[1][]" value="'.$product1." "."-"." ".$price1.'" />';echo $product1;
print '<input type="text" name="products[1][]" value="" />QTY';print '<br>';
print '<br>';print '<br>';
print '
<input type="submit" name="formSubmit" value="Submit" />
</form>';
?>