How to insert Session data in database - php

Im trying to save my cart item into database.
This is what i tried and it didnt work, can anyone please help me.
if (isset($_POST['submit']))
{
include ('config.php');
foreach ($_SESSION["products"] as $cart_itm)
{
$kod_barang = $cart_itm["kod_barang"];
$nama_barang = $cart_itm["nama_barang"];
$kuantiti = $cart_itm["qty"];
$insert_row = $mysqli->query("INSERT INTO `maklumat_permohonan`(`kod_barang`, `nama_barang`, `kuantiti`, `nombor_order`)
VALUES ('$kod_barang','$nama_barang','$kuantiti')");
if($insert_row){
print 'Please keep the Transaction ID for future reference<br />';
?>
Back
<?php
}else{
die('Error : ('. $mysqli->errno .') '. $mysqli->error);
}
}
}
This is how my cart session look like, im sorry if my code is not too decent and proper, as this is my early learning in PHP using session for my thesis in Server client topics.
if(isset($_SESSION["products"]))
{
$total = 0;
echo '<form method="post" action="simpan_permohonan.php">';
echo '<ul>';
$cart_items = 0;
foreach ($_SESSION["products"] as $cart_itm)
{
$product_code = $cart_itm["code"];
$results = $mysqli->query("SELECT nama_barang,jenis_barang FROM data_barang WHERE kod_barang='$product_code' LIMIT 1");
$obj = $results->fetch_object();
echo '<li class="cart-itm">';
echo '<span class="remove-itm"> ×</span>';
echo '<div class="product-info">';
echo '<h3>'.$obj->nama_barang.' (Code :'.$product_code.')</h3> ';
echo '<div class="p-qty">Kuantiti : '.$cart_itm["qty"].'</div>';
echo '<div>'.$obj->jenis_barang.'</div>';
echo '</div>';
echo '</li>';
$subtotal = ($cart_itm["price"]*$cart_itm["qty"]);
$total = ($total + $subtotal);
echo '<input type="hidden" name="item_name['.$cart_items.']" value="'.$obj->nama_barang.'" />';
echo '<input type="hidden" name="item_code['.$cart_items.']" value="'.$product_code.'" />';
echo '<input type="hidden" name="item_desc['.$cart_items.']" value="'.$obj->jenis_barang.'" />';
echo '<input type="hidden" name="item_qty['.$cart_items.']" value="'.$cart_itm["qty"].'" />';
$cart_items ++;
}
echo '</ul>';
echo '<span class="check-out-txt">';
echo '<input type="submit" value="Simpan" />';
echo '</span>';
echo '</form>';
}else{
echo 'Troli Anda Kosong';
}

As you don;t share exact error, I'm just guessing that your INSERT statement is not escaped and probably occurrence of ' breaks SQL.
You should seriously take a look at prepared statements, otherwise your application is very vulnerable to SQL injection.

Related

calculating the sum of an array php

Hi im currently doing making a website that sells games as a project but im having problems calculating the sum for the price of the games
I have this loop which displays the games added into the basket
cart.php
<?php
$count = 0;
while ($count < $numrow)
{
$row = $results -> fetch_assoc();
extract($row);
echo"<div>";
echo"<div class='recommended_games'>";
echo "<img src='images/".$gameIMG."' />";
echo "</div>";
echo '<div class="price_tag">';
echo '<div class="price_tag" name="price" method="POST">£'.$gamePrice. '</div>';
echo'</div>';
echo '<div id="update_form"><form action="updatebasket.php" method="POST" name="updateform">';
echo '<select name="quantity" id="quantity" />';
echo '<option value="1">1</option>';
echo '<option value="2">2</option>';
echo '<option value="3">3</option>';
echo '<option value="4">4</option>';
echo '<option value="5">5</option>';
echo '</select>';
echo '<input type="hidden" value="'.$gameID.'" name="gameid" id="gameid" />';
echo '<input type="submit" value="update" />';
echo '</form>';
echo '<div class="quantity_update">';
echo '<form action="remove_item.php" method="POST">';
echo '<input type="hidden" value="'.$gameID.'" name="gameid" id="gameid" />';
echo '<input type="submit" value="Remove Item" />';
echo '</form>';
echo '</div>';
echo '</div>';
echo"<img class='box1' src='Images/Grey-Banners.png' />";
echo"</div>";
$count = $count + 1;
}
echo '<div id="delete_all">';
echo '<form action="delete_cart.php" method="POST">';
echo '<input id="hide_button" type="submit" value="Clear All" />';
$a=array($gamePrice);
echo array_sum($a);
echo '</form>';
echo '</div>';
?>
this is where im trying to calculate the total price
$a=array($gamePrice);
echo array_sum($a);
The reason this doesnt work, is because $gamePrice never is an array (unless you didnt provide all code). In the loop, it gets set to a new value, after the loop only the last one is stored.
Based on some hints in your code, I guessing this is a cart and you're looping through the cart. An easy way to get a total is like this:
$total = 0;
while( $itemsThatWeLoop){
// Some code here
$total+= $gamePrice*$quantity;
}
You add a variable which increments with the product's price
To explain the while-only-last-value-saved:
$i=0;
while( $i<=10){
$i= $i+1;
}
echo $i;
Will give 10. All other iterations $i gets set to a new value. The original value is not saved

Update the quantity of cart using PHP & SQL

I've this problem in which I can't update the cart for some reason. I've looked for many solutions to see if they can solve my problem but no luck. I've 2 files one called cart.php which contains the form and a updatebasket.php file which contains query.
Cart file
<?php
$count = 0;
while ($count < $numrow)
{
$row = $results -> fetch_assoc();
extract($row);
echo"<div>";
echo"<div class='recommended_games'>";
echo "<img src='images/".$gameIMG."' />";
echo "</div>";
echo '<div class="price_tag">';
echo '<div class="price_tag">£'.$gamePrice. '</div>';
echo'</div>';
echo '<div id="update_form"><form action="updatebasket.php" method="POST" name="updateform">';
echo '<input type="text" value="1" name="quantity" id="quantity" />';
echo '<input type="hidden" value="'.$gameID.'" name='.$gameID.' id="gameid" />';
echo '<input type="submit" value="update" />';
echo '</form>';
echo '</div>';
echo"<img class='box1' src='Images/Grey-Banners.png' />";
echo"</div>";
$count = $count + 1;
}
?>
updatebasket file
<?php
session_start();
require "dbconnect.php";
$memberID = $_SESSION['id'];
$quantity = $_POST['quantity'];
$gameID = $_POST['gameid'];
mysqli_autocommit($con,FALSE);
$connect->query($query);
$query = "UPDATE basket SET quantity = ".$quantity." WHERE gameid = ".$gameID." AND id = ".$memberID."";
$results = $connect->query($query);
mysqli_commit($con);
header('Location: cart.php');
?>
Change cart.php to this:
<?php
$count = 0;
while ($count < $numrow)
{
$row = $results -> fetch_assoc();
extract($row);
echo"<div>";
echo"<div class='recommended_games'>";
echo "<img src='images/".$gameIMG."' />";
echo "</div>";
echo '<div class="price_tag">';
echo '<div class="price_tag">£'.$gamePrice. '</div>';
echo'</div>';
echo '<div id="update_form"><form action="updatebasket.php" method="POST" name="updateform">';
echo '<input type="text" value="1" name="quantity" id="quantity" />';
echo '<input type="hidden" value="'.$gameID.'" name="gameid" id="gameid" />';
echo '<input type="submit" value="update" />';
echo '</form>';
echo '</div>';
echo"<img class='box1' src='Images/Grey-Banners.png' />";
echo"</div>";
$count = $count + 1;
}
?>
The big change is this:
BEFORE:
echo '<input type="hidden" value="'.$gameID.'" name='.$gameID.' id="gameid" />';
AFTER:
echo '<input type="hidden" value="'.$gameID.'" name="gameid" id="gameid" />';
php uses the name attribute as the key for post and get, not id.
id is used by javascript, jquery (also javascript), css, and probably a few other things.
But in forms, name is the one you want for the post and get key.

Function not Inserting Values in wordpress

function name_to_match($nametocheck){
global $wpdb,$namematch,$nomatchfound;
$query="select * from currency";
$namematch=$wpdb->get_col($query,1);
//echo $namematch;
foreach($namematch as $namet){
//echo $name;
if($namet == $nametocheck){
echo "Name Already Exists<br />";
$nomatchfound=0;
}
}
}
function add_signal_form(){
global $wpdb,$insert,$nametocheck;
echo "<br /><br /><br />";
$nametocheck=trim($_POST['name']);
$sign=trim($_POST['sign']);
$status=$_POST['status'];
if(isset($_POST['submit'])){
//..................Function to call if name exist it will not add
name_to_match($nametocheck);
if($nomatchfound ==0){
echo "Match Found";}
else
{
$insert= $wpdb->insert('currency',array('name'=>$nametocheck,'sign'=>$sign,'status'=>$status));
if(!$insert){
echo "Currency Not Added Query Fails";
}
else
{
echo "Currency Successfully Added";
}
}
}
echo '<form name="form1" method="post" action="">';
echo '<div class="label">';
echo '<label for="name">Name</label>';
echo '<div class="field">';
echo '<input type="text" name="name" id="name">';
echo '</div>';
echo '<div class="label">';
echo '<label for="sign">Sign</label>';
echo '</div>';
echo '<div class="field">';
echo '<input type="text" name="sign" id="sign">';
echo '</div>';
echo '<div class="label">';
echo '<label for="status">Status</label>';
echo '</div>';
echo '<div class="field">';
echo '<select name="status" id="status">';
echo '<option value="1">Publish</option>';
echo '<option value="0">Draft</option>';
echo '</select>';
echo '</div>';
echo '<div class="submit">';
echo '<input type="submit" name="submit" id="submit" value="Save Currency">';
echo '</div>';
echo '</p>';
echo '</form>';
/*
echo "<form action='' name=form1\" id=\"form1\" method=\"post\">";
echo '<input type="text" name="text" id="text">';
echo '<input type="submit" name="submit" value="Add New Signal">';
//wp_dropdown_pages();
echo "</form>";
*/}
This function working properly if name exist it return exists but when it not exist nothing happen no else clause fire what is the problem. I am doing something wrong . i want after checking it submit the form and show success message when currency added but nothing happening i try whole the day long and at last i fails in it suggest me
As #akirk suggested, you're never setting $nomatchfound to true or 1 in your name_to_match function.
But there are some other things you could do to make the code clearer and quicker. For example, name_to_match could return a value, instead of setting a global variable. And you could use the database to check for $nametocheck, rather than looping over all the values in the table - it'll make your code shorter and it'll run quicker. So I'd change name_to_match to something like this:
function name_to_match($nametocheck){
global $wpdb;
$query = $wpdb->prepare("select count(*) from currency where name = %s", $nametocheck);
$matching_row_count = $wpdb->get_var($query);
return $matching_row_count;
}
Then the start of your add_signal_form function becomes
function add_signal_form(){
global $wpdb;
echo "<br /><br /><br />";
$nametocheck=trim($_POST['name']);
$sign=trim($_POST['sign']);
$status=$_POST['status'];
if(isset($_POST['submit'])){
$existing_rows = name_to_match($nametocheck);
if($existing_rows != 0){
echo "Match Found";
}
else {
$insert= $wpdb->insert('currency',array('name'=>$nametocheck,'sign'=>$sign,'status'=>$status));
if (!$insert) {
echo "Currency Not Added Query Fails";
}
else {
echo "Currency Successfully Added";
}
}
}

update quantity with one button php

Hello i am currently doing a project to make a website that sells game however one of my problems right now is updating the quantity with a single button. i have got it working with multiple update buttons next to the items that i would like to update but to make it more realistic, i would like to just have one button that will update all the item quantities in the basket table in my database.
This is my cart file, i have commented out the bit where it works with multiple update buttons.
<?php
$count = 0;
while ($count < $numrow)
{
$row = $results -> fetch_assoc();
extract($row);
echo"<div>";
echo"<div class='recommended_games'>";
echo "<img src='images/".$gameIMG."' />";
echo "</div>";
echo '<div class="price_tag">';
echo '<div class="price_tag">£'.$gamePrice. '</div>';
echo'</div>';
echo '<div id="update_form"><form action="updatebasket.php" method="POST" name="updateform" id="update_all">';
echo '<select name="quantity" id="quantity" />';
echo '<option value="1">1</option>';
echo '<option value="2">2</option>';
echo '<option value="3">3</option>';
echo '<option value="4">4</option>';
echo '<option value="5">5</option>';
echo '</select>';
//echo '<input type="hidden" value="'.$gameID.'" name="gameid" id="gameid" />';
//echo '<input type="submit" value="update" />';
echo '</form>';
echo '</div>';
echo '</form>';
echo"<img class='box1' src='Images/Grey-Banners.png' />";
echo"</div>";
$count = $count + 1;
}
echo '<input type="hidden" value="'.$gameID.'" name="gameid" id="gameid" form="update_all"/>';
echo '<input type="submit" value="update" form="update_all"/>';
?>
This is my updatebasket file which updates the quantity in the database
<?php
session_start();
require "dbconnect.php";
$memberID = $_SESSION['id'];
$quantity = $_POST['quantity'];
$gameID = $_POST['gameid'];
$connect->query($query);
$query = "UPDATE basket SET quantity = ".$quantity." WHERE gameid = ".$gameID." AND id = ".$memberID."";
$results = $connect->query($query);
mysqli_commit($con);
header('Location: cart.php');
?>
If I understand you correctly, you need to work with an array for this to be achieved, by changing your form and you can use a foreach to assemble your query to update each entry in the cart. So one button will update each item in the cart with the respective quantities. I did not test this code, this is how I would approach it.
Eample of the HTML Form Changes:
echo '<div id="update_form"><form action="updatebasket.php" method="POST" name="updateform" id="update_all">';
echo '<select name="quantity[]" id="quantity" />';
echo '<option value="1">1</option>';
echo '<option value="2">2</option>';
echo '<option value="3">3</option>';
echo '<option value="4">4</option>';
echo '<option value="5">5</option>';
echo '</select>';
//echo '<input type="hidden" value="'.$gameID.'" name="gameid[]" id="gameid" />';
//echo '<input type="submit" value="update" />';
echo '</form>';
echo '</div>';
echo '</form>';
echo"<img class='box1' src='Images/Grey-Banners.png' />";
echo"</div>";
$count = $count + 1;
}
echo '<input type="hidden" value="'.$gameID.'" name="gameid[]" id="gameid" form="update_all"/>';
echo '<input type="submit" value="update" form="update_all"/>';
?>
Query Eample:
foreach ($_POST['gameid'] as $row=>$id) {
$gameid = $id;
$newquantity = ($_POST['quantity'][$row]);
$query = "UPDATE basket SET quantity = ".$newquantity." WHERE gameid = ".$gameID." AND id = ".$memberID."";
$connect->query($query);
}
One solution would be to give your quantity <select> inputs unique names with the Game ID attached to the end (eg. "quantity_32"). This makes it easy to know how much of each game is in the cart.
// POST Example
$_POST['quantity_32'] = 1;
$_POST['quantity_31'] = 3;
$_POST['quantity_37'] = 2;
Front-End Form Change
echo '<select name="quantity_<?=$gameID?>" id="quantity" />';
Back-End Processing
Then on the processing page loop through the $_POST variables and find the quantity fields and grab their Game ID's.
foreach ($_POST as $key => $quantity) {
// Ignore non-quantity fields
if (preg_match('/quantity_([0-9]+)/i', $key, $result) !== 1) continue;
$quantity = (int)$quantity;
$game_id = (int)$result[1];
// Update Cart Quantity in DB
// ...
}
Important!
Please ensure you SQL-Escape all values you save into the DB. Hackers could do some nasty stuff if you don't.
This example shows how you can keep things safe using MySQLi Prepared Statements.
http://mattbango.com/notebook/code/prepared-statements-in-php-and-mysqli/

How do I get values from a table out of a foreach loop?

What I'm doing is trying to set up a page where users can see their created tools and delete them whenever they want. I'm querying three different tables and putting the results into an array. Once those values are in an array, a foreach loop goes through and populates a table with all the information in a table, like so:
$counter = 1;
echo '<table>'
foreach ($recent_saved_tools as $key => $value) {
echo '<tr name="item'.$counter.'">';
echo '<td>';
echo '<input type="hidden" name="tablename" value="'.$value['table'].'" />';
echo '<input type="hidden" name="tabledelete" value="'.$value['delete'].'" />';
echo '<input type="hidden" name="tableidfield" value="'.$value['idfield'].'" />';
echo '<input type="hidden" name="tableid" value="'.$value['id'].'" />';
//code to display the tool name and link
echo '<a style="text-decoration:none;" href="'.WEBSITE.'tools/'.$value['URL'].'?saved_data_id='.$value['id'].'">'.$value['display'].'</a><br />';
echo date("m/d/Y H:i:s", $key).'<br />';
echo '</td><td>';
//code to display the delete button
echo ' <input class="cssformbutton bluebutton" type="button" name="delete" id="deletebtn'.$counter.'" value="Delete" /><br /><br /><br /><br /></td>';
$counter ++;
}
echo '</table>';
The problem is whenever I run the SQL query, no matter what button I click it always takes the values from the last table row. I know it has something to do with the way they're named (multiple elements have the same name) but I'm at a loss on how to fix this. Any help would be appreciated.
Here's the query I'm using to delete the item:
$query = 'UPDATE '.$value['table'].' SET '.$value['delete'].' = 1 WHERE '.$value['idfield'].' = '.$value['id'];
$sql->query($query);
EDIT: added delete code
Every row has some inputs which are posted to the server. They have the same names - for every row. You could change it like this:
echo '<input type="hidden" name="tablename'.$counter.'" value="'.$value['table'].'" />';
Then you can use $_POST['tablename'.$rownr] in your delete code.
Doesn't look like you're closing the anywhere...
What results return from the query?
What output are you expecting?
try making it a for loop in stead and adding the variable to the end.
$array;
$counter = count($array);
echo '<table>'
for($i = 0; $i < $counter - 1; $i++) {
echo '<tr name="item'.$i.'">';
echo '<td>';
echo '<input type="hidden" name="tablename" value="'.$value['table']. $i'" />';
echo '<input type="hidden" name="tabledelete" value="'.$value['delete']. $i'" />';
echo '<input type="hidden" name="tableidfield" value="'.$value['idfield']. $i'" />';
echo '<input type="hidden" name="tableid" value="'.$value['id'].'" />';
//code to display the tool name and link
echo '<a style="text-decoration:none;" href="'.WEBSITE.'tools/'.$value['URL'].'?saved_data_id='.$value['id'].'">'.$value['display'].'</a><br />';
echo date("m/d/Y H:i:s", $key).'<br />';
echo '</td><td>';
//code to display the delete button
echo ' <input class="cssformbutton bluebutton" type="button" name="delete" id="deletebtn'.$counter.'" value="Delete" /><br /><br /><br /><br /></td>';
}
echo '</table>';

Categories