I have this code bellow:
<?php
if(isset($_SESSION["products"])) {
$total = 0;
echo '<form action="cart-post-config.php" enctype="multipart/form-data" method="POST">>';
foreach ($_SESSION["products"] as $cart_itm) {
echo '<tr>';
echo '<td></td>';
echo '<td><input type="text" name="product_name[]" value="'.$cart_itm["name"].'"/></td>';
echo '<td><input type="text" name="product_price[]" value="'.$cart_itm["price"].'"/></td>';
echo '<td><input type="text" name="product_quantity[]" value="'.$cart_itm["qty"].'"/></td>';
$totalPerEach = ($cart_itm["price"]*$cart_itm["qty"]);
echo '<td><input type="text" name="product_eachTotal[]" value="'.$totalPerEach.'"/></td>';
echo '<td>View Save Delete</td>';
echo '</tr>';
}
echo '<input type="submit" name="submit" />';
echo '</form>';//close the form
}
else {
echo 'Your Cart is empty'; }
?>
The code above is used to collect the cart information of the member, where the information that has been collected are putted to the input of the form that will be posted to the database.
This is the config:
if($_SERVER["REQUEST_METHOD"] == "POST")
{
for($i=0; $i<count($_POST['product_name']);$i++)
{
$product_name=$_POST['product_name'][$i];
$product_price=$_POST['product_price'][$i];
$product_quantity=$_POST['product_quantity'][$i];
$product_eachTotal=$_POST['product_eachTotal'][$i];
mysql_query("insert into member_cart (cart_code, product_cart_name, product_cart_price, product_cart_quantity, total_cart_price)
values(0, '$product_name', '$product_price', '$product_quantity', '$product_eachTotal')");
}
}
The config above will be read the form that will be posted where will loop the row of eahc products that have been added to the chart.
My problem now is after posting the form, the row of product_cart_quantityand the row of total_cart_price' only got the text/data ofArray` in the database.
Please help I don't have any idea what I am doing wrong here.
Thanks
You have set $product_price to 3 different values which ends up being product_eachTotal. Following is the corrected code.
if($_SERVER["REQUEST_METHOD"] == "POST") {
for($i=0; $i<count($_POST['product_name']);$i++) {
$product_name=$_POST['product_name'][$i];
$product_price=$_POST['product_price'][$i];
$product_quantity=$_POST['product_quantity'][$i];
$product_eachTotal=$_POST['product_eachTotal'][$i];
mysql_query("insert into member_cart (cart_code, product_cart_name, product_cart_price, product_cart_quantity, total_cart_price)
values(0, '$product_name', '$product_price', '$product_quantity', '$product_eachTotal')");
}
}
Related
I want to insert into my mysql database only those rows that have a checked checkbox at the end.
Since i have several tables and table data cells that have the same name, then my data is stored in arrays (product_name[] etc.):
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<?php
while($res = mysqli_fetch_array($result)) {
echo "<table id='tbl'>
<thead><th name='category[]'>".$res['category_name']."</th></thead>
<tbody>
<tr>
<td><input name='product_name[]' id='name' type='text'></td>
<td><input name='quantity[]' type='text' value='1'></td>
<td><input type='checkbox' name='check[]'></td>
</tr>
</tbody>";
}
?>
</table>
<div class="bottom-btn">
<button id="submit" type="submit">Lisa märgitud külmkappi</button>
</div>
</form>
Do i have to store the checkboxes in array as well (check[])?
My php code for the insert:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$product_name = $_POST['product_name'];
$quantity = $_POST['quantity'];
// $check = $_POST['check'];
foreach($product_name as $i=>$product_name)
{if(!empty($product_name)){
$sql = "INSERT INTO products (id, product_name, category, quantity, expiration_date, barcode) VALUES ('','$product_name', '', '$quantity[$i]', '', '')";
if($stmt = mysqli_prepare($conn, $sql)){
mysqli_stmt_bind_param($stmt, "ss",$param_product_name, $param_quantity);
$param_product_name = $product_name;
$param_quantity=$quantity;
if(mysqli_stmt_execute($stmt)){
header("location: myFridge.php");
} else{
echo "Something went wrong. Please try again later.";
}
mysqli_stmt_close($stmt);
}
}
}
mysqli_close($conn);
}
So far i have tried this: if(!empty($_POST['check'])) and this if(isset($_POST['check']) , but those did not work.
How to check if checkbox is checked before inserting data to database?
EDIT. WORKING.
I added this code to my page to make an array of checkbox on and off values:
function getAllCheckboxValues($check){
$found = array();
foreach ($check as $key => $val){
if($val == 'on'){
$found[] = $key;
}
}
foreach($found as $kev_f => $val_f){
unset($check[$val_f-1]);
}
$final_arr = array();
return $final_arr = array_values($check);
}
$checkbox_arr = getAllCheckboxValues($_POST['check']);
And also added a hidden input before every checkbox:
<input type='hidden' name='check[]' value='off'>
Then matched the checbox array with my products array and voila!
You could simply var_dump($_POST) to see whats in your post request. That always helps when facing issues like that.
Checkboxes come with the value on if they are checked and off if they are not, so it will never be empty and always be set, which is why your checks did not work. You should check if($_POST['check'] === 'on') instead.
I want to print the checklist array value, here checklist is dynamically created for each row of Food table. How I can do that ? If I click submit no value is submitted I guess so, How to use submit button? In fact where to use ..plz help me
<?php // File: anyco.php
require('anyco_ui.inc.php');
// Create a database connection
$conn = oci_connect('system','123','localhost/orcl');
ui_print_header('FoodItemList');
//session_start();
//$cid=$_SESSION['cid'];
//do_query($conn, 'SELECT Fooditem_ID,Food_item_name,price,day_available,time_available,discount_percentage,start_date,deadline FROM Food_Item');
ui_print_footer(date('Y-m-d H:i:s'));
function do_query($conn, $query)
{
$stid = oci_parse($conn, $query);
$r = oci_execute($stid,OCI_DEFAULT);
print '<table border="1">';
print '<tr>';
print '<td>Food_ID<td>Food_Name<td>Price(tk)<td>Dvailable_day<td>Avaliable_time<td>Discount<td>Dis_start date<td>Dis_finish date<td>selected item<td>quanity';
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS))
{
print '<tr>';
$num=1;
$val="";
foreach ($row as $item)
{
if($num==1)
{
$val = $item;
$num=2;
}
print '<td>'.($item!== null ? htmlentities($item) : ' ').'</td>';
}
//echo$val;
echo '<td><input type="checkbox" name = "invite[]" value="$val>" </td>';
echo '<td><input type="number" name = "name[]" ></td>';
print '</tr>';
}
print '</table>';
}
if(isset($_POST['submit']))
{
if (is_array($_POST['invite']))
{
foreach($_POST['invite'] as $key=>$name)
{
echo $key, '=>', $name,'<br/>';
//Here $key is the array index and $name is the value of the checkbox
}
}
}
?>
<html>
<style>
body
{
background:orange;
}
</style>
<body text="green">
<br><br>
<form method="post">
<?php do_query($conn, 'SELECT Fooditem_ID,Food_item_name,price,day_available,time_available,discount_percentage,start_date,deadline FROM Food_Item'); ?>
<input type ="submit" value="submit" name="submit"><br><br>
</form>
</body>
</html>
Your form doesn't have any inputs inside it because you are calling your function way before you print out the form tags.
This line needs to move to within the form:
do_query($conn, 'SELECT Fooditem_ID,Food_item_name,price,day_available,time_available,discount_percentage,start_date,deadline FROM Food_Item');
So that the code looks like this, and the whole table with its inputs is printed inside the form tags. I also added a name for the submit button:
<form method="post">
<?php do_query($conn, 'SELECT Fooditem_ID,Food_item_name,price,day_available,time_available,discount_percentage,start_date,deadline FROM Food_Item'); ?>
<input type ="submit" value="submit" name="submit"><br><br>
</form>
Finally, when you echo values into your inputs, there are two syntax errors in this line:
echo '<td><input type="checkbox" name = "invite[]" value="$val>" </td>';
You can echo a variable into a string in several ways - here are two. 1) if the variable is between single quotes, PHP will automatically convert the variable to its value. In this case, it's double quotes, so no go. 2) You start your echo command with single quotes, so you can break out of the string with a single quote, concatenate the variable with a period, and then break back in to the string with another single quote, like this:
echo '<td><input type="checkbox" name = "invite[]" value="' . $val . '"> </td>';
I'm converting my code from extremely long GET statements (is that the correct word?) into separate files for each page. The code I'm about to show worked fine before I moved it to it's own file.
The page's full code is:
<?
require_once('./inc/glob_head.php');
$database->openConnection();
$listOfGamesQuery = $database->queryDB("SELECT * FROM mainSite_games");
if (isset($_GET) && $_GET['action'] == 'deleteGame')
{
$gameID = $_GET['gameID'];
$database->queryDB("DELETE FROM mainSite_games WHERE id='$gameID'");
redir('viewGames.php');
}
elseif (isset($_GET) && $_GET['action'] == 'editGame')
{
$gameID = $_GET['gameID'];
$gameNameQry = $database->queryDB("SELECT gameName FROM mainSite_games WHERE id='$gameID'");
while ($gameNameDta = $database->fetchArray($gameNameQry))
{
$gameName = $gameNameDta['gameName'];
}
$gameDescQry = $database->queryDB("SELECT gameDesc FROM mainSite_games WHERE id='$gameID'");
while ($gameDescDta = $database->fetchArray($gameDescQry))
{
$gameDesc = $gameDescDta['gameDesc'];
}
?>
<form name="editGame" id="editGame" action="viewGames.php?action=processEdit&gameID=<? echo $gameID; ?>" method="POST">
<input type="text" name="gameName" value="<? echo stripslashes($gameName); ?>" /><br />
<textarea name="gameDesc" class="span12" rows="10"><? echo stripslashes($gameDesc); ?></textarea><br />
<input type="submit" name="submitEditGame" class="btn btn-primary" />
</form>
<?
}
elseif (isset($_GET) && $_GET['action'] == 'processEdit')
{
$gameID = $_GET['gameID'];
$gameName = $database->escapeString($_POST['gameName']);
$gameDesc = $database->escapeString($_POST['gameDesc']);
$database->queryDB("UPDATE mainSite_games SET gameName='$gameName' WHERE id='$gameID'");
$database->queryDB("UPDATE mainSite_games SET gameDesc='$gameDesc' WHERE id='$gameID'");
redir('viewGames.php');
} else {
echo '<div class="contCont">';
echo '<table>';
echo '<thead>';
echo '<tr>';
echo '<th>Game Name</th>';
echo '<th>Delete</th>';
echo '<th>Edit</th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';
while ($listOfGames = $database->fetchAssoc($listOfGamesQuery)) {
echo '<tr>';
print '<td>' . stripslashes($listOfGames['gameName']) . '</td>';
print '<td>Delete</td>';
print '<td>Edit</td>';
echo '</tr>';
}
echo '</tbody>';
echo '</table>';
echo '</div>';
echo '</div>';
echo '</div>';
echo '</body>';
echo '</html>';
}
$database->closeConnection();
?>
glob_head just provides the database class, the database connection, the functions file requirement, and styling/page structure that is constant around the site. Having stated this, the $database calls are not mistakes, and are actually defined elsewhere.
Now the problem is, in the above code, the editGame elseif block pulls information from the database successfully, therefore I assume that it must be getting the information correctly. Now, when a user clicks submit, it'll take them to the next block, processEdit, and that for some reason makes the fields blank and sets the blank values in the database. I have no idea what's going on. Maybe this needs a fresh set of eyes? Thanks in advance.
For your reference, the 'redir' calls are a custom function that uses javascript redirection instead of relying on headers. I find it cleaner, and possibly easier to use than changing the structure of the code.
You are submitting METHOD="POST" but looking at the $_GET superglobal variable. The $_GET variable is empty, because there is no GET submission being made.
Change all instances of $_GET to $_REQUEST (or $_POST), or change METHOD="POST" to "METHOD="GET".
I use the code from phpwebcommerce's shopping cart tutorial, and I am trying to add a text field for user to insert quantity. Since there are different number of choices for a single product, so I use the while statement to query the sub-items and put a text field plus a add button beside each of them. But it only takes the quantity for the first item, and not the rest. If I insert a quantity for the first item, and click on "add" on any of other items, it will still store the first in my cart, which it should not... I am stuck... can someone help me out?
<?php
function displayprodDetail($pdId)
{
$query = mysql_query("SELECT * FROM product_image WHERE p_id ='$pdId'");
WHILE($datarows = mysql_fetch_array($query))
{
$p_num = $datarows['p_number'];
echo '<h1><span>'.$p_num.' -- $'.$datarows['price'].'</span></h1>';
echo '<div id="prodPic"><img src ="'.$datarows['image'].'"/><br /></div>';
echo '<div id="items">';
$sql = mysql_query("SELECT * FROM items WHERE item_number LIKE '$p_num/%' ORDER BY item_number ASC");
$numProduct = dbNumRows($sql);
if($numProduct > 1)
{
echo '<table border="0" cellspacing="0">';
WHILE($data = mysql_fetch_array($sql))
{
$itemId = $data['item_id'];
$p_num = $data['item_number'];
echo '<tr>';
echo '<td><INPUT TYPE="HIDDEN" NAME="'.$itemId.'" VALUE="'.$itemId.'">'.$p_num.'</td>';
echo '<td> Qty: <input type="number" name="qty" id="qty" style="width:30px"></td>';
$cart_url = "cart.php?action=add&i=$itemId&qty=";
?>
<td><input type="Submit" name="Submit" value="Add" onClick="window.location.href='<?php echo $cart_url; ?>' +document.getElementById('qty').value;" ></td>
<?php
echo '</tr>';
}
echo '</table>';
}
else
{
echo 'Items are currently not available.<br>Contact us for more detail.';
}
echo '</div>';
}
}
?>
Here is the add to cart function:
function addToCart()
{
// make sure the product id exist
if (isset($_GET['i']) && (int)$_GET['i'] > 0)
{
$itemId = (int)$_GET['i'];
}
else
{
header('Location: home.php');
}
if (isset($_GET['qty']) && (int)$_GET['qty'] > 0)
{
$qty = (int)$_GET['qty'];
}
// current session id
$sid = session_id();
// check if the product is already
// in cart table for this session
$sql = mysql_query("SELECT item_id FROM cart_table WHERE item_id = $itemId AND ct_session_id = '$sid'");
if (dbNumRows($sql) == 0)
{
// put the product in cart table
$sql = mysql_query("INSERT INTO cart_table (item_id, ct_qty, ct_session_id, ct_date) VALUES ($itemId, $qty, '$sid', now())");
}
else
{
// update product quantity in cart table
$sql = mysql_query("UPDATE cart_table SET ct_qty = ct_qty + $qty WHERE ct_session_id = '$sid' AND item_id = $itemId");
}
// an extra job for us here is to remove abandoned carts.
// right now the best option is to call this function here
deleteAbandonedCart();
header('Location: ' . $_SESSION['shop_return_url']);
}
since you are naming your input boxes same, that's why its not working as expected, try something like:
<input type="number" name="qty_<?php echo $itemId; ?>" id="qty_<?php echo $itemId; ?>" style="width:30px">...
...
<td><input type="Submit" name="Submit" value="Add" onClick="window.location.href='<?php echo $cart_url; ?>' +document.getElementById('qty_<?php echo $itemId; ?>').value;" ></td>
What i have is a array of items from my mySQL database and each item has a checkbox. i am trying to make it so when you click on the checkbox it will submit the information to the database for the item that got checked or unchecked. have i have it is unchecked = 1 and checked = 0. this is for where i want to display the item.
Now my issue is I can't seem to get anything to submit into my database, I don't understand jQuery enough to be able to write a function for it, so i need some help. here is what i got for my code.
if(isset($_POST['submit'])){
foreach($_POST['id'] as $id){
$value = (isset($_POST['location'][$id]) && $_POST['location'][$id]=="0" ? '0' : '1');
$insert = mysql_query("UPDATE items SET location='$value' WHERE id='$id'") or die('Insert Error: '.mysql_error());
}
}
echo '<form id="form1" method="post"><input type="submit" name="submit" value="Submit">';
$result = mysql_query("SELECT * FROM items")
or die("Query Failed: ".mysql_error());
$counter = 0;
echo '<div class="specialcontainer">';
while($row = mysql_fetch_array($result)){
list($id, $item_info, $item_img, $price, $sale, $location) = $row;
if($location == '0'){
$set_checked = ' checked="checked" ';
}else{
$set_checked = '';
}
if($counter % 5==0) {
echo '</div>';
echo '<div class="specialcontainer">';
}
echo '<div class="special"><img src="../images/items/'.$item_img.'" width="130" /><br />';
echo $item_info.'<br />';
echo 'Reg. $'.$price.'<br />';
echo 'Sale $'.$sale.'<br />';
echo 'Slide Show: <input type="checkbox" id="ch" value="0" name="location['.$id.']"'.$set_checked.' /><br />';
echo '<input type="button" value="Edit" name="edit" onclick="window.location.href=\'specials.php?action=edit&id='.$id.'\'">';
echo '<input type="button" value="Delete" name="Delete" onclick="window.location.href=\'specials.php?action=delete&id='.$id.'\'">';
echo '<input type="hidden" name="id[]" value='.$id.' />';
echo '</div>';
$counter++;
}
echo '</div>';
echo '<input type="submit" name="submit" value="Submit"></form>';
so as you can see, i do have the submit button there, but my plan is to remove it for the onChange submit. I've tried the onchange="this.form.submit();" in the checkbox parameter but it don't work properly. so i just want it to submit anytime a checkbox gets clicked on kinda thing.
Would an Ajax solution like this work?
$('ch').click(function() {
//this is what goes into $_POST
var data = 'id='+ $(this).attr('name') +'&checked=' + $(this).is(':checked');
$.ajax({
//This would be the url that would handle updating the MySQL Record
url: my_mysql_handler.php,
cache: false,
type: 'POST',
data: data,
success: function(response) {
alert(response); //or whatever you want to do with the success/fail notification
}
});
});
You should try document.getElementById('form1').submit() in the onchange method of your checkbox