cart libraries in codeigniter not work - php

i have some problem in my libraries cart when i try to insert my product into the cart. could you help me.
here is my code link for product into the cart.
<form method="post" action="<?php echo base_url(); ?>cart/add">
<span style="width: 70%;"><input type="submit" class="fa fa-cart-arrow-down btn btn-primary btn-sm btn-block" value="Add to Cart" <?php echo "$mati";?>/></span>
<input type="hidden" name="id_books" value="<?php echo $row->id_books; ?>"/>
<input type="hidden" name="id_category" value="<?php echo $row->id_category; ?>"/>
<input type="hidden" name="title" value="<?php echo $row->title; ?>"/>
<input type="hidden" name="images" value="<?php echo $row->images; ?>"/>
<input type="hidden" name="price" value="<?php echo $total; ?>"/>
<input type="hidden" name="qty" value="1"/>
</form>
and this is cart controller
class Cart extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->library(array('cart'));
session_start();
}
function index()
{
$data['menu'] = 'cart';
$this->load->view('v_cart', $data);
}
function add()
{
$data = array(
'id_books' => $this->input->post('id_books'),
'id_category' => $this->input->post('id_category'),
'qty' => $this->input->post('qty'),
'price' => $this->input->post('price'),
'images' => $this->input->post('images'),
'title' => $this->input->post('title'));
$this->cart->insert($data);
/*print_r($data);*/
/*echo "<meta http-equiv='refresh' content='0; url=".base_url()."cart/'>";*/
redirect('cart','refresh');
}
and this is cart view
<?php if($cart = $this->cart->contents()):
?>
<?php echo form_open('cart/update'); ?>
<table id="cart-table" class="table table-condensed">
<thead>
<tr>
<th>Action</th>
<th>Image</th>
<th>Product</th>
<th>Price</th>
<th>Quanity</th>
<th>Sub Total</th>
</tr>
</thead>
<tbody>
<?php $i = 1; ?>
<?php foreach($cart as $item): /* $title = str_replace(' ', '-', $item['title']); ?>
<?php $price = $row['price']; $jumlah_desimal = "0"; $pemisah_desimal =""; $pemisah_ribuan =".";?>
<?php /*echo form_hidden('rowid[]', $item['rowid']);*/
echo form_hidden($i.'[rowid]', $item['rowid']); ?>
<tr>
<th class="product-remove">
<a class="remove" title="Remove this product" href="<?php echo base_url().'cart/delete/'.$item['rowid'];?>">×</a>
</th>
<th>
<div class="media">
<div class="relative">
<a href="shop-single.html" title="">
<img src="<?php echo base_url().$item['images'];?>" alt=""/>
</a>
</div>
</div><!-- end media -->
</th>
<th>
<?php echo $item['title'];?>
</th>
<td>Rp. <?php echo $this->cart->format_number($item['price']); /*echo rupiah($item['price']); */?></td>
<td>
<?php echo form_input(array('name' => $i.'[qty]', 'value' => $item['qty'], 'maxlength' => '3', 'class' => 'j')); ?> pcs
</td>
<td>
Rp. <?php echo $this->cart->format_number($item['subtotal']);/*echo rupiah($item['subtotal']);*/ ?>
</td>
</tr>
<?php $i++; ?>
<?php endforeach; ?>
<tr>
<td colspan="5" style="text-align: right!important;"><b>Total </b>(biaya buku)</td>
<td>
Rp. <?php echo $this->cart->format_number($this->cart->total()); ?>
</td>
</tr>
</tbody>
</table>
<?php
echo form_close();
else:
echo 'Sorry, Your Cart is empty';
endif;
?>
the result always show
Sorry, Your Cart is empty
where is the bug? anybody can help me :)
thanks :)

Codeigniter cart has predefined format:
https://ellislab.com/codeigniter/user-guide/libraries/cart.html
$data = array(
'id' => 'sku_123ABC',
'qty' => 1,
'price' => 39.95,
'name' => 'T-Shirt',
'options' => array('Size' => 'L', 'Color' => 'Red')
);
$this->cart->insert($data);
So you code will be,
function add()
{
$data = array(
'id'=>someID,
'name'=>SomeName,
'qty' => $this->input->post('qty'),
'price' => $this->input->post('price'),
'options' =>array('id_books'=> $this->input->post('id_books'),'id_category'=> $this->input->post('id_category'),'images' => $this->input->post('images'),'title' => $this->input->post('title'));
$this->cart->insert($data);
/*print_r($data);*/
/*echo "<meta http-equiv='refresh' content='0; url=".base_url()."cart/'>";*/
redirect('cart','refresh');
}

Related

Values from textbox array not updating

I'm new in this forum and I'm having a hard time updating selected value from checkbox coming from the textbox value.
Scenario:
I want to update selected items, For example, I want to update Item-2 and the textbox from item received will be enabled, I will enter a number for example 1 and the textbox from total receive will automatically sum using AJAX.
The problem is after submitting the value from total receive the records that were updating is blank, but when I try to check and print_r the value is there.
And one more thing if all checkboxes are checked and enter a number for each item received, the value that it only get is the last value and will be updated will all selected checkbox.
Notes:
The checkbox is an array
Textbox from total receive is an array
Here's my UI:
Controller:
public function recitem_insert(){
$this->load->model('dbquery');
$check = $this->input->post('check');
$total_rec = $_POST['total_rec'];
if(isset($check)){ //Check if check is checked
for($i=0;$i<sizeof($check);$i++){
for($j=0;$j<sizeof($total_rec);$j++){
$updateData = array('rec_qty' => $total_rec[$j] );
$this->dbquery->modUpdatedynamicval('tblstock', 'id', $updateData, $check[$i]);
}
}//end for loop
echo "<script type='text/javascript'>
alert('Successfully Added!');
window.close();
</script>";
}else{ //End If
echo 'Please select a checkbox';
}
}
View:
<form method="post" action="<?php echo base_url() ?>user/recitem_insert">
<div class="box">
<div class="box-header">
<h3 class="box-title">System ID: <b><?php echo $process_id; ?></b></h3>
</div>
<!-- /.box-header -->
<div class="box-body">
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<th>Action</th>
<th>Item Code</th>
<th>Item Description</th>
<th>Required QTY Order</th>
<th>Last QTY Recieve</th>
<th>Item Recieve</th>
<th>Total Recieve</th>
</tr>
</thead>
<tbody>
<?php
$query = $this->db->query("SELECT * FROM tblstock where process_id = '$process_id'");
foreach ($query->result() as $row){
?>
<tr>
<td><input type="checkbox" name="check[]" id="opt" value="<?php echo $row->id; ?>" onclick="valueChanged()"> </td>
<td><?php echo $row->item_code; ?></td>
<td><?php echo $row->description; ?></td>
<td><?php echo $row->qty_order; ?></td>
<td><?php echo $row->rec_qty; ?></td>
<input type="hidden" name="last_item_rec[]" value="<?php echo $row->rec_qty; ?>">
<td><input type="text" name="item_rec[]" id="txt" disabled=""></td>
<td><input type="text" name="total_rec[]"></td>
</tr>
<?php
}
?>
</tbody>
<tfoot>
</tfoot>
</table>
</div>
<!-- /.box-body -->
</div>
<div class="box-footer">
<button type="submit" class="btn bg-olive btn-flat margin">Submit</button>
</div>
</form>
Model:
public function modUpdatedynamicval($table, $column, $data, $equal_to){
$this->db->where($column, $equal_to);
$this->db->update($table, $data);
}
Edit
Let's assume:
I've input 1 in item_receive textbox one and the total receive will be 10,
2 in item_receive textbox two and the total receive will be 11,
3 in item_receive textbox three and the total receive will be 12,
CODE:
$check = $this->input->post('check');
$total_rec = $_POST['total_rec'];
echo 'Check Value';
print_r($check);
echo '<br><br>';
echo 'Total Recieve';
print_r($total_rec);
OUTPUT:
Check ValueArray ( [0] => 1 [1] => 2 [2] => 3 )
Total RecieveArray ( [0] => 10 [1] => 11 [2] => 12 )
But If I only input the second textbox here's the output:
Check ValueArray ( [0] => 2 )
Total RecieveArray ( [0] => [1] => 11 [2] => )
From what I see, you are having a problem to determine which input index is which on the back end. You could set an index key on each of the input like this :
<tbody>
<?php
$query = $this->db->query("SELECT * FROM tblstock where process_id = '$process_id'");
foreach ($query->result() as $key => $row){ //added key to be used as inputs key
?>
<tr>
<td><input type="checkbox" name="check[<?php echo $key ?>]" id="opt" value="<?php echo $row->id; ?>" onclick="valueChanged()"> </td>
<td><?php echo $row->item_code; ?></td>
<td><?php echo $row->description; ?></td>
<td><?php echo $row->qty_order; ?></td>
<td><?php echo $row->rec_qty; ?></td>
<input type="hidden" name="last_item_rec[<?php echo $key ?>]" value="<?php echo $row->rec_qty; ?>">
<td><input type="text" name="item_rec[<?php echo $key ?>]" id="txt" disabled=""></td>
<td><input type="text" name="total_rec[<?php echo $key ?>]"></td>
</tr>
<?php
}
?>
</tbody>
After that, then replace the for loop :
for($i=0;$i<sizeof($check);$i++){
for($j=0;$j<sizeof($total_rec);$j++){
$updateData = array('rec_qty' => $total_rec[$j] );
$this->dbquery->modUpdatedynamicval('tblstock', 'id', $updateData, $check[$i]);
}
}//end for loop
With this foreach :
foreach ($check as $key => $item) {
$updateData = array('rec_qty' => $total_rec[$key] );
$this->dbquery->modUpdatedynamicval('tblstock', 'id', $updateData, $check[$key]);
}
So you don't manually check for the total_rec value but instead it only checks on submitted check post data.
from what i can see, like everybody else is saying, you have trouble in finding the correct rows of checked item.
I suggest you edit the way you name the form in multidimensional array. bet you didnt know that?
so in view.php
<form method="post" action="<?php echo base_url() ?>user/recitem_insert">
<div class="box">
<div class="box-header">
<h3 class="box-title">System ID: <b><?php echo $process_id; ?></b></h3>
</div>
<!-- /.box-header -->
<div class="box-body">
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<th>Action</th>
<th>Item Code</th>
<th>Item Description</th>
<th>Required QTY Order</th>
<th>Last QTY Recieve</th>
<th>Item Recieve</th>
<th>Total Recieve</th>
</tr>
</thead>
<tbody>
<?php
//WTF?? it's 2019. Say hello to SQL Injection
$query = $this->db->query("SELECT * FROM tblstock where process_id = '$process_id'");
foreach ($query->result() as $i=>$row){
?>
<tr>
<td><input type="checkbox" name="data[<?php echo $i;?>][check]" id="opt" value="<?php echo $row->id; ?>" onclick="valueChanged()"> </td>
<td><?php echo $row->item_code; ?></td>
<td><?php echo $row->description; ?></td>
<td><?php echo $row->qty_order; ?></td>
<td><?php echo $row->rec_qty; ?></td>
<input type="hidden" name="data[<?php echo $i;?>][last_item_rec]" value="<?php echo $row->rec_qty; ?>">
<td><input type="text" name="data[<?php echo $i;?>][item_rec]" id="txt" disabled=""></td>
<td><input type="text" name="data[<?php echo $i;?>][total_rec]"></td>
</tr>
<?php
}
?>
</tbody>
<tfoot>
</tfoot>
</table>
</div>
<!-- /.box-body -->
</div>
<div class="box-footer">
<button type="submit" class="btn bg-olive btn-flat margin">Submit</button>
</div>
</form>
and you can easily cycle through the data for each rows while at the same time validating if the checkbox is checked
<?php
//simple way of traversing the data
if ( isset( $_POST['data'] ) )
{
echo '<table>';
foreach ( $_POST['data'] as $d )
{
//you have all the data here
//start checking on checked box
if(isset($d['check']))
{
echo '<tr>';
echo ' <td>', $d['last_item_rec'], '</td>';
echo ' <td>', $d['item_rec'], '</td>';
echo ' <td>', $d['total_rec'], '</td>';
echo '</tr>';
}
}
echo '</table>';
}
Can try with row key (item id). Update your array key with $row->id.
<tbody>
<?php
$query = $this->db->query("SELECT * FROM tblstock where process_id = '$process_id'");
foreach ($query->result() as $row){
?>
<tr>
<td><input type="checkbox" name="check[]" id="opt" value="<?php echo $row->id; ?>" onclick="valueChanged()"> </td>
<td><?php echo $row->item_code; ?></td>
<td><?php echo $row->description; ?></td>
<td><?php echo $row->qty_order; ?></td>
<td><?php echo $row->rec_qty; ?></td>
<input type="hidden" name="last_item_rec[<?php echo $row->id; ?>]" value="<?php echo $row->rec_qty; ?>">
<td><input type="text" name="item_rec[<?php echo $row->id; ?>]" id="txt" disabled=""></td>
<td><input type="text" name="total_rec[<?php echo $row->id; ?>]"></td>
</tr>
<?php
}
?>
</tbody>
Scenraio Like:
1 item Id "2"
2 item Id "3"
3 item Id "5"
If you check first st row and first row item_id ($row->id) is 2 and enter 7 than you will get array like :-
print_r($_POST['total_rec']);
Output Like:
Array([2]=>7)
You can easy to find data using array key
Update:
<form method="post" action="<?php echo base_url(); ?>">
<div class="box">
<div class="box-header">
<h3 class="box-title">
System ID: <b> <?php echo '12'; ?></b>
</h3>
</div>
<!-- /.box-header -->
<div class="box-body">
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<th> Action</th>
<th>Item Code </th>
<th>Item Description</th>
<th>Required QTY Order</th>
<th>Last QTY Recieve</th>
<th>Item Recieve</th>
<th>Total Recieve</th>
</tr>
</thead>
<tbody>
<?php
//$query = $this->db->query("SELECT * FROM tblstock where process_id = '$process_id'");
$new_item_list = array(
array('id'=> '1','item_code'=> 'ITEM-1','description' => 'ITEM Desc', 'qty_order'=> '2','rec_qty'=> '2'),
array('id'=> '2','item_code'=> 'ITEM-2','description' => 'ITEM Desc 2', 'qty_order'=> '3','rec_qty'=> '3' ),
array('id'=> '3','item_code'=> 'ITEM-3','description' => 'ITEM Desc', 'qty_order'=> '5','rec_qty'=> '4' ),
array('id'=> '4','item_code'=> 'ITEM-4','description' => 'ITEM Desc', 'qty_order'=> '1','rec_qty'=> '3' )
);
foreach ($new_item_list as $row){
?>
<tr>
<td><input type="checkbox" name="<?php echo $row['id']; ?>[check]" id="opt" value="<?php echo $row['id']; ?>" onclick="valueChanged()"> </td>
<td><?php echo $row['item_code']; ?></td>
<td><?php echo $row['description']; ?></td>
<td><?php echo $row['qty_order']; ?></td>
<td><?php echo $row['rec_qty']; ?></td>
<input type="hidden" name="<?php echo $row['id']; ?>[last_item_rec]" value="<?php echo $row['rec_qty']; ?>">
<td><input type="text" name="<?php echo $row['id']; ?>[item_rec]" id="txt" value='' ></td>
<td><input type="text" name="<?php echo $row['id']; ?>[total_rec]" value=''>
</td>
</tr>
<?php
}
?>
</tbody>
<tfoot>
</tfoot>
</table>
</div>
<!-- /.box-body -->
</div>
<div class="box-footer">
<button type="submit" class="btn bg-olive btn-flat margin">Submit</button>
</div>
</form>
Submit Action: For example
foreach($_POST as $key => $value){
if(isset($value['check'])){
//Row ID of item table $key
$total = $value['total_rec'] * $value['item_rec'];
echo "Total Number :".$total."</br>";
#here is your update query
}
}
Link:- https://prnt.sc/mswdoc
If check checkbook and submit from then you will get output like
Output:- https://prnt.sc/mswefv
Your checkboxes all have the same ID, which always leads to problems. Change the id of the checkbox in the loop.
<td><input type="checkbox" name="check[]" id="opt-<?php echo $row->id; ?>" value="<?php echo $row->id; ?>" onclick="valueChanged()"> </td>

Submit button not adding items to shopping cart in my PHP page

I'm trying to follow a simple add to cart tutorial using php, sql, with my database on phpmyadmin, but when the user clicks "add to cart", nothing is displayed in the shopping cart table.
Any non-php solutions are welcome.
Here is the tutorial: http://www.webslesson.info/2016/08/simple-php-mysql-shopping-cart.html
Thank you!
<?php
session_start();
require_once ('database_conn.php');
if (isset($_POST["add_to_cart"])) {
if (isset($_SESSION["shopping_cart"])) {
$item_array_id = array_column($_SESSION["shopping_cart"], "productID");
if (!in_array($_GET["id"], $item_array_id)) {
$count = count($_SESSION["shopping_cart"]);
$item_array = array(
'productID' => $_GET["productID"],
'productName' => $_POST["productName"],
'productPrice' => $_POST["productPrice"],
'productAisle' => $_POST["productAisle"]
);
$_SESSION["shopping_cart"][$count] = $item_array;
}
} else {
$item_array = array(
'productID' => $_GET["productID"],
'productName' => $_POST["productName"],
'productPrice' => $_POST["productPrice"],
'productAisle' => $_POST["productAisle"]
);
$_SESSION["shopping_cart"][0] = $item_array;
}
}
if (isset($_GET["action"])) {
if ($_GET["action"] == "delete") {
foreach ($_SESSION["shopping_cart"] as $keys => $values) {
if ($values["item_id"] == $_GET["id"]) {
unset($_SESSION["shopping_cart"][$keys]);
echo '<script>alert("Item Removed")</script>';
echo '<script>window.location="add.php"</script>';
}
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<br />
<div class="container" style="width:700px;">
<?php
$name = isset($_REQUEST['name']) ? $_REQUEST['name'] : null;
$sqlProducts = "SELECT productID, productName, productPrice, productImage, productAisle
FROM s_products WHERE productName LIKE '%$name%'";
$rProducts = mysqli_query($conn, $sqlProducts) or die(mysqli_error($conn));
while ($row = mysqli_fetch_assoc($rProducts)) {
$productID = $row['productID'];
$productName = $row['productName'];
$productImage = $row['productImage'];
$productAisle = $row['productAisle'];
{
?>
<div class="col-md-4">
<form method="post" action="add.php?action=add&id=<?php echo $row["id"]; ?>">
<div style="border:1px solid #333; background-color:#f1f1f1; border-radius:5px; padding:16px;" align="center">
<img src="<?php echo $row["productImage"]; ?>" class="img-responsive" /><br />
<h4 class="text-info"><?php echo $row["productName"]; ?></h4>
<h4 class="text-danger">$ <?php echo $row["productPrice"]; ?></h4>
<input type="text" name="quantity" class="form-control" value="1" />
<input type="hidden" name="hidden_name" value="<?php echo $row["productName"]; ?>" />
<input type="hidden" name="hidden_price" value="<?php echo $row["productPrice"]; ?>" />
<input type="submit" name="add_to_cart" style="margin-top:5px;" class="btn btn-success" value="Add to Cart" />
</div>
</form>
</div>
<?php
}
}
?>
<div style="clear:both"></div>
<br />
<h3>Order Details</h3>
<div class="table-responsive">
<table class="table table-bordered">
<tr>
<th width="40%">Item Name</th>
<th width="10%">Quantity</th>
<th width="20%">Price</th>
<th width="15%">Total</th>
<th width="5%">Action</th>
</tr>
<?php
if (!empty($_SESSION["shopping_cart"])) {
$total = 0;
foreach ($_SESSION["shopping_cart"] as $keys => $values) {
?>
<tr>
<td><?php echo "$productName"; ?></td>
<td><?php echo "$productPrice"; ?></td>
<td>$ <?php echo "$productAisle"; ?></td>
<td><a href="add.php?action=delete&id=<?php echo "$productID";
}
?>"><span class="text-danger">Remove</span></a></td>
</tr>
<tr>
<td colspan="3" align="right">Total</td>
<td align="right">$ <?php echo number_format($total, 2); ?></td>
<td></td>
</tr>
<?php
}
?>
</table>
</div>
</div>
<br />
</body>
</html>
Giving you a whole reworked code base for you.
<?php
session_start();
require_once('database_conn.php');
if (isset($_POST["add_to_cart"])) {
if (isset($_SESSION["shopping_cart"]) && !empty($_SESSION['shopping_cart'])) {
$item_array_id = array_column($_SESSION["shopping_cart"], "productID");
if (!in_array($_GET["id"], $item_array_id)) {
$count = count($_SESSION["shopping_cart"]);
$item_array = array(
'productID' => $_GET["productID"],
'productName' => $_POST["productName"],
'productPrice' => $_POST["productPrice"],
'productAisle' => $_POST["productAisle"]
);
$_SESSION["shopping_cart"][$count] = $item_array;
}
} else {
$item_array = array(
'productID' => $_GET["productID"],
'productName' => $_POST["productName"],
'productPrice' => $_POST["productPrice"],
'productAisle' => $_POST["productAisle"]
);
$_SESSION["shopping_cart"][0] = $item_array;
}
}
if (!empty($_GET["action"])) {
switch ($_GET['action']) {
case 'delete':
foreach ($_SESSION["shopping_cart"] as $keys => $values) {
if ($values["item_id"] == $_GET["id"]) {
unset($_SESSION["shopping_cart"][$keys]);
echo '<script>alert("Item Removed")</script>';
echo '<script>window.location="add.php"</script>';
}
}
break;
case 'add':
if (isset($_SESSION["shopping_cart"]) && !empty($_SESSION['shopping_cart'])) {
$item_array_id = array_column($_SESSION["shopping_cart"], "productID");
if (!in_array($_GET["id"], $item_array_id)) {
$count = count($_SESSION["shopping_cart"]);
$item_array = array(
'productID' => $_GET["productID"],
'productName' => $_POST["productName"],
'productPrice' => $_POST["productPrice"],
'productAisle' => $_POST["productAisle"]
);
$_SESSION["shopping_cart"][$count] = $item_array;
}
} else {
$item_array = array(
'productID' => $_GET["productID"],
'productName' => $_POST["productName"],
'productPrice' => $_POST["productPrice"],
'productAisle' => $_POST["productAisle"]
);
$_SESSION["shopping_cart"][0] = $item_array;
}
break;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<br/>
<div class="container" style="width:700px;">
<?php
$name = isset($_REQUEST['name']) ? $_REQUEST['name'] : null;
$sqlProducts = "SELECT productID, productName, productPrice, productImage, productAisle
FROM s_products WHERE productName LIKE '%$name%'";
$rProducts = mysqli_query($conn, $sqlProducts) or die(mysqli_error($conn));
while ($row = mysqli_fetch_assoc($rProducts)) {
?>
<div class="col-md-4">
<form method="post" action="add.php?action=add&productID=<?php echo $row["id"]; ?>">
<div style="border:1px solid #333; background-color:#f1f1f1; border-radius:5px; padding:16px;"
align="center">
<img src="<?php echo $row["productImage"]; ?>" class="img-responsive"/><br/>
<h4 class="text-info"><?php echo $row["productName"]; ?></h4>
<h4 class="text-danger">$ <?php echo $row["productPrice"]; ?></h4>
<input type="text" name="quantity" class="form-control" value="1"/>
<input type="hidden" name="productName" id="productName" value="<?= $row["productName"] ?>"/>
<input type="hidden" name="productPrice" id="productPrice" value="<?= $row["productPrice"] ?>"/>
<input type="hidden" name="productAisle" id="productAisle" value="<?= $row['productAisle'] ?>"/>
<input type="hidden" name="hidden_name" value="<?php echo $row["productName"]; ?>"/>
<input type="hidden" name="hidden_price" value="<?php echo $row["productPrice"]; ?>"/>
<input type="submit" name="add_to_cart" style="margin-top:5px;" class="btn btn-success"
value="Add to Cart"/>
</div>
</form>
</div>
<?php
}
?>
<div style="clear:both"></div>
<br/>
<h3>Order Details</h3>
<div class="table-responsive">
<table class="table table-bordered">
<tr>
<th width="40%">Item Name</th>
<th width="10%">Quantity</th>
<th width="20%">Price</th>
<th width="15%">Total</th>
<th width="5%">Action</th>
</tr>
<?php
if (!empty($_SESSION["shopping_cart"])) {
$total = 0;
foreach ($_SESSION["shopping_cart"] as $keys => $values) {
?>
<tr>
<td><?= $values['productName'] ?></td>
<td><?= $values['productPrice'] ?></td>
<td>$ <?= $values['productAisle'] ?></td>
<td><span class="text-danger">Remove</span>
</td>
</tr>
<?php
}
?>
<tr>
<td colspan="3" align="right">Total</td>
<td align="right">$ <?php echo number_format($total, 2); ?></td>
<td></td>
</tr>
<?php
}
?>
</table>
</div>
</div>
<br/>
</body>
</html>

Codeigniter 3.x, Validation Always Passes Whether Checkbox Checked or Not

I am trying to make selecting one checkbox from a total of four checkboxes required but it's not working. Whether I select a checkbox or not, it always passes validation.
Here is my method in my controller Cargo_inquiry() {}
function step_two() {
$country_to_select = $this->session->userdata('freight_address_country');
$this->data['users'] = $this->My_Users_Model->get_companies_list($country_to_select);
// load up the validation rules for blog Info form
$this->config->load('validate_cargo');
$this->form_validation->set_rules($this->config >item('validate_cargo_create_step_two') );
if ($this->form_validation->run('validate_cargo_create_step_two') === FALSE) {
echo "FALSE";
// die;
$this->load->view('_layouts/main/template1', $this->data);
} else {
echo "TRUE";
// die;
redirect('/Cargo_inquiry/step_three');
}
}
Here is my validation rules located in validate_cargo.php:
$config['validate_cargo_create_step_two'] = array(
'user_id' => array(
'field' => 'user_id',
'label' => '',
'rules' => 'required',
'errors' => array(
'required' => 'Please select at least one company.',
),
),
);
Here is my view/form:
<?php echo form_open('Cargo_inquiry/step_three',array('class'=>'form-horizontal'));?>
<table class="table table-bordered table-striped" id="mytable">
<thead>
<tr>
<th width="3%">Select</th>
<th>company</th>
<th>location</th>
<th>rating</th>
<th>web</th>
<th>Associations/serv_hhgpe</th>
</tr>
</thead>
<tbody>
<?php
foreach ($users as $user) { ?>
<tr>
<td>
<?php // echo form_checkbox('user_id[]', 'user_id[]', set_checkbox("user_id[]"), "Company"); ?>
<input type="checkbox" name="user_id" value="<?php echo $user->id; ?>" />
</td>
<td>
<?php echo $user->company ?>
</td>
<td>
<?php echo $user->city ?>
</td>
<td>
<?php echo $user->state_province ?>
</td>
<td>
<?php echo $user->name ?>
</td>
<td style="text-align:center" width="200px">
</td>
</tr>
<?php } ?>
</tbody>
</table>
<?php echo form_submit('cargo_create_step_two', 'Next->', 'class="btn btn-primary btn-lg btn-block"');?>
<?php echo form_close();?>
Arrrgg!!! I was submitting to the wrong form :( So very sorry.

Save session data to table

I am after two bits of advice for a project I am working on and would really appreciate any advice you may have..
I have the below code and its working really well as a shopping cart for a student project. At the end of the code, I would like to save all the items added to the shopping cart in the table at the bottom to a MySQL table called orders for example.
Is this possible to do?
Also, for each item for sale on the page there is an image. Is it possible hover over the image and the description from the MySQL table is shown in a hover box?
<?php
session_start();
$connect = mysqli_connect("localhost", "root", "", "WineCellar");
if(isset($_POST["add_to_cart"]))
{
if(isset($_SESSION["shopping_cart"]))
{
$item_array_id = array_column($_SESSION ["shopping_cart"], "item_id");
if(!in_array($_GET["id"], $item_array_id))
{
$count = count($_SESSION["shopping_cart"]);
$item_array = array(
'item_id' => $_GET["id"],
'item_name' => $_POST["hidden_name"],
'item_price' => $_POST["hidden_price"],
'item_quantity' => $_POST["quantity"]
);
$_SESSION["shopping_cart"][$count] = $item_array;
}
else
{
echo '<script>alert("Item Already Added")</script>';
echo '<script>window.location="Shop.php"</script>';
}
}
else
{
$item_array = array(
'item_id' => $_GET["id"],
'item_name' => $_POST["hidden_name"],
'item_price' => $_POST["hidden_price"],
'item_quantity' => $_POST["quantity"]
);
$_SESSION["shopping_cart"][0] = $item_array;
}
}
if(isset($_GET["action"]))
{
if($_GET["action"] == "delete")
{
foreach($_SESSION["shopping_cart"] as $keys => $values)
{
if($values["item_id"] == $_GET["id"])
{
unset($_SESSION["shopping_cart"][$keys]);
echo '<script>alert("Item Removed")</script>';
echo '<script>window.location="shop.php"</script>';
}
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>The Wine Cellar</title>
<script src="style/jquery.min.js"></script>
<link rel="stylesheet" href="style/bootstrap.min.css" />
<script src="style/bootstrap.min.js"></script>
</head>
<body>
<br />
<div class="container" style="width:700px;">
<h3 align="center"><img src="Images/slide1.jpg" width="644" height="176"></h3>
<p align="center"><br />
<?php
$query = "SELECT * FROM tbl_product ORDER BY id ASC";
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
?>
</p>
<div class="col-md-4">
<form method="post" action="shop.php?action=add&id=<?php echo $row["id"]; ?>">
<div style="border:1px solid #333; background-color:#f1f1f1; border-radius:5px; padding:16px;" align="center">
<img src="<?php echo $row["image"]; ?>" class="img-responsive" /><br />
<h4 class="text-info"><?php echo $row["name"]; ?></h4>
<h4 class="text-danger">$ <?php echo $row["price"]; ?></h4>
<input type="text" name="quantity" class="form-control" value="1" />
<input type="hidden" name="hidden_name" value="<?php echo $row["name"]; ?>" />
<input type="hidden" name="hidden_price" value="<?php echo $row["price"]; ?>" />
<input type="submit" name="add_to_cart" style="margin-top:5px;" class="btn btn-success" value="Add to Cart" />
</div>
</form>
</div>
<?php
}
}
?>
<div style="clear:both"></div>
<br />
<h3>Order Details</h3>
<div class="table-responsive">
<table class="table table-bordered">
<tr>
<th width="40%">Item Name</th>
<th width="10%">Quantity</th>
<th width="20%">Price</th>
<th width="15%">Total</th>
<th width="5%">Action</th>
</tr>
<?php
if(!empty($_SESSION["shopping_cart"]))
{
$total = 0;
foreach($_SESSION["shopping_cart"] as $keys => $values)
{
?>
<tr>
<td><?php echo $values["item_name"]; ?></td>
<td><?php echo $values["item_quantity"]; ?></td>
<td>$ <?php echo $values["item_price"]; ?></td>
<td>$ <?php echo number_format($values["item_quantity"] * $values["item_price"], 2); ?></td>
<td><span class="text-danger">Remove</span></td>
</tr>
<?php
$total = $total + ($values["item_quantity"] * $values["item_price"]);
}
?>
<tr>
<td colspan="3" align="right">Total</td>
<td align="right">$ <?php echo number_format($total, 2); ?></td>
<td></td>
</tr>
<?php
}
?>
</table>
</div>
</div>
<br />
</body>
</html>
Thanks in advance
Shane

Why are my values not matching my wordpress options?

I am working on the settings page for a plugin I am writing. There is a form field that let's the user select which currency symbol they want to use when displaying prices. I have created a function that easily displays select menus and determines which option should be selected based on the option stored in the database. For some reason, nothing is being selected in the select menu of the form.
This is the plugin code for this page...
<?php
function hc_options() {
?>
<div class="wrap">
<h2>HeadChef Settings</h2>
<form method="post" action="options.php">
<?php settings_fields( 'my-cool-plugin-settings-group' ); ?>
<?php do_settings_sections( 'my-cool-plugin-settings-group' ); ?>
<table class="form-table">
<tr valign="top">
<th scope="row">Currency Format</th>
<td>
<?php echo select_menu('currency_format', array('1' => '$12.50', '2' => '$12,50'), esc_attr( get_option('currency_format'))); ?>
</td>
</tr>
<tr valign="top">
<th scope="row">Currency Character</th>
<td><?php
$options = array(
htmlspecialchars('º') => 'º Generic',
htmlspecialchars('$') => '$ Dollar',
htmlspecialchars('£') => '£ Pound',
htmlspecialchars('¥') => '¥ Yen',
htmlspecialchars('€') => '€ Euro',
htmlspecialchars('₱') => '₱ Peso'
);
echo select_menu('currency_prefix', $options, htmlspecialchars(esc_attr(get_option('currency_prefix')))); ?></td>
</tr>
<tr valign="top">
<th scope="row">Currency Suffix <br><small>(I.E. USD... Leave blank to disable.)</small></th>
<td><input type="text" name="currency_suffix" value="<?php echo esc_attr( get_option('currency_suffix') ); ?>" /></td>
</tr><tr>
<th scope="row">Enable Dish Ratings</th>
<td>
<fieldset><?php echo radio_buttons('Enable Dish Ratings', 'enable_dish_ratings', array('1' => 'Yes', '2' => 'No'), esc_attr(get_option('enable_dish_ratings'))); ?>
</td>
</tr><tr>
<th scope="row">Description Character Limit <small>Leave blank for no limit</small></th>
<td><input type="text" name="description_char_limit" value="<?php echo esc_attr( get_option('description_char_limit') ); ?>"></td>
</tr>
</table>
<?php submit_button(); ?>
</form>
</div>
<?php }
function select_menu($title, $options, $selected){
$output = '<select name="'.$title.'">\r\n';
if(count($options) > 0){
foreach($options as $val => $label){
$output .= '<option value="'.$val.'"';
if($val == $selected){
$output .= ' SELECTED';
}
$output .= '>'.$label."</option>\r\n";
}
}
$output .= "</select>\r\n";
return $output;
} ?>
Apparently the esc_attr function was screwing with it and the currency_prefix option was parsed as $ instead of $.

Categories