i am still relatively new to php and this site, so i apologise now!This is driving me crazy, i'm trying to add an array to session state for a shopping cart i am piecing together from different bits of code....
$_SESSION['cart_items'] =
array(
'product_name' => $name,
'productId' => $id,
'quantity' => 1
);
^that is the part where it adds to the session state, this works fine as i printr and it comes out like this
Array ( [product_name] => The Ned Rose [productId] => 1 [quantity] => 1 )
This is the bit that i cant get to work. How do i access the product ID's so i can use them in a SQL query to fetch the data to populate the cart...
if(count($_SESSION['cart_items'])>0){
$ids = "";
foreach($_SESSION['cart_items']['productId'] as $id=>$value){
$ids = $ids . $id . ",";
}
Thanks,
EDIT HERE THE CART PAGE
can anyone see where i am going wrong?
<?php
session_start();
$page_title="Cart";
include 'mysql.php';
print_r($_SESSION['cart_items']);
$action = isset($_GET['action']) ? $_GET['action'] : "";
$name = isset($_GET['name']) ? $_GET['name'] : "";
if($action=='removed'){
echo "<div class='alert alert-info'>";
echo "<strong>{$name}</strong> was removed from your cart!";
echo "</div>";
}
else if($action=='quantity_updated'){
echo "<div class='alert alert-info'>";
echo "<strong>{$name}</strong> quantity was updated!";
echo "</div>";
}
if(count($_SESSION['cart_items'])>0){
$ids = "";
$ids = array_keys($_SESSION['cart_items']);
foreach($_SESSION['cart_items'][$id] as $key=>$value){
$ids = $ids . $id . ",";
}
// remove the last comma
$ids = rtrim($ids, ',');
//start table
echo "<table class='table table-hover table-responsive table-bordered'>";
// our table heading
echo "<tr>";
echo "<th class='textAlignLeft'>Product Name</th>";
echo "<th>Price (GBP)</th>";
echo "<th>Action</th>";
echo "</tr>";
$query = "SELECT prodID, prodName, prodPrice FROM product_tbl WHERE prodID IN ({$ids}) ORDER BY prodName";
$result = mysqli_query($db, $query);
$total_price=0;
while ($row = mysqli_fetch_assoc($result)){
extract($row);
echo "<tr>";
echo "<td>".$row['prodName']."</td>";
echo "<td>£".$row['prodPrice']."</td>";
echo "<td>";
echo "<a href='remove_from_cart.php?id=".$row['prodID']."&name=".$row['prodName']."' class='btn btn-danger'>";
echo "<span class='glyphicon glyphicon-remove'></span> Remove from cart";
echo "</a>";
echo "</td>";
echo "</tr>";
$total_price+=$row['prodPrice'];
}
echo "<tr>";
echo "<td><b>Total</b></td>";
echo "<td>£{$total_price}</td>";
echo "<td>";
echo "<a href='#' class='btn btn-success'>";
echo "<span class='glyphicon glyphicon-shopping-cart'></span> Checkout";
echo "</a>";
echo "</td>";
echo "</tr>";
echo "</table>";
}
else{
echo "";
echo "No products found in your cart! Click Here To Return To The Store";
echo "";
}
?>
Use $id as the KEY value when storing the product in the cart:
$_SESSION['cart_items'][$id] =
array(
'product_name' => $name,
'productId' => $id,
'quantity' => 1
);
Then you can use the ID in the foreach loop:
if( count($_SESSION['cart_items']) > 0){
foreach($_SESSION['cart_items']['productId'] as $id => $value){
// Get data for this product
}
}
You could add products to the array so that you didn't need to directly store the "productId" value.
// Set data
$_SESSION['cart_items'][$id] = Array('name'=>$name,'qty'=>1);
// Show session content
foreach($_SESSION['cart_items'] as $id=>$props){
echo 'id='.$id.'<br />';
echo 'name='.$props['name'].'<br />';
echo 'qty='.$props['qty'];
}
// Collect ids (result is an array of ids)
$ids = array_keys($_SESSION['cart_items'];
// Use $ids in a query
$sql = "SELECT * FROM your_table WHERE id_field IN('".implode("','",$ids)."')";
You can use the followings
$_SESSION['cart_items'][] =
array(
'product_name' => $name,
'productId' => $id,
'quantity' => 1
);
or (this will update previously added product id in the cart)
$_SESSION['cart_items'][$id] =
array(
'product_name' => $name,
'productId' => $id,
'quantity' => 1
);
if(count($_SESSION['cart_items'])>0){
$ids = "";
foreach($_SESSION['cart_items'] as $id=>$value){
$ids = $ids . $id . ",";
}
}
Related
How to echo the left column table to "Daily" "Monthly" and "Yearly"? It currently displays repeatedly because the results of SQL queries on the right side are 3 items.
$ID = get_current_user_id();
global $wpdb;
if(isset($_GET["view_data"])){
$SubmissionID = $_GET["view_data"];
$results = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}myTable WHERE user_id = {$ID} AND `key` IN ('name1', 'name2', 'name3')", OBJECT );
if(isset($_GET["form_name"])) echo "<h4>YOUR REVIEW ON {$_GET["form_name"]}</h4>";
echo "<table>";
foreach ($results as $result) {
echo "<tr>";
echo "<td>";
echo "<p>test1</p>";
echo "</td>";
echo "<td>";
echo $result->value;
echo "</td>";
echo "</tr>";
}
echo "</table>";
echo "<h4><a href='?view_all'>Back to List</a></h4>";
}
The current output of my code:
test1
dynamic_data_1
test1
dynamic_data_2
test1
dynamic_data_3
The output I need:
Daily
dynamic_data_1
Monthly
dynamic_data_2
Yearly
dynamic_data_3
add a counter:
$ID = get_current_user_id();
global $wpdb;
if(isset($_GET["view_data"])){
$SubmissionID = $_GET["view_data"];
$results = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}myTable WHERE user_id = {$ID} AND `key` IN ('name1', 'name2', 'name3')", OBJECT );
if(isset($_GET["form_name"])) echo "<h4>YOUR REVIEW ON {$_GET["form_name"]}</h4>";
$count = 0;
echo "<table>";
foreach ($results as $result) {
$count++;
$title = 'DEFAULT Title';
if( $count == 1 ){
$title = 'Daily';
}
elseif( $count == 2 ){
$title = 'Monthly';
}
elseif( $count == 3 ){
$title = 'Yearly';
}
echo "<tr>";
echo "<td>";
echo "<p>" . $title ."</p>";
echo "</td>";
echo "<td>";
echo $result->value;
echo "</td>";
echo "</tr>";
}
echo "</table>";
echo "<h4><a href='?view_all'>Back to List</a></h4>";
}
I would like to create a billing system. This system should show on their profile a 20$ reoccurring payment for the services they suscribed at.
If they add a new one to their account, the statement have to update the new amount (for example 30$) depending on the service they selected.
I've already created a cart in PHP, I know how to add items to my cart and do a checkout. I'm just a bit confused about how I would make this unique for every individual user.
Add to cart.
<?php
session_start();
// Get the product id
$id = isset($_GET['id']) ? $_GET['id'] : "";
$name = isset($_GET['name']) ? $_GET['name'] : "";
$quantity = isset($_GET['quantity']) ? $_GET['quantity'] : "";
//Check if the cart array was created
//If it isn't, create the cart array
if(!isset($_SESSION['cart_items'])){
$_SESSION['cart_items'] = array();
}
//Check if the item is in the array, if it is, do not add
if(array_key_exists($id, $_SESSION['cart_items'])){
// redirect to product list and tell the user it was added to cart
header('Location: products.php?action=exists&id' . $id . '&name=' . $name);
}
//If not, then add the item to the array
else{
$_SESSION['cart_items'][$id]=$name;
//Redirects to product list
header('Location: products.php?action=added&id' . $id . '&name=' . $name);
}
?>
Cart page:
<?php
session_start();
$page_title="Cart";
include 'layout_head.php';
$action = isset($_GET['action']) ? $_GET['action'] : "";
$name = isset($_GET['name']) ? $_GET['name'] : "";
if($action=='removed'){
echo "<div class='Wow danger'>";
echo "<strong>{$name}</strong> was removed from your cart.";
echo "</div>";
}
else if($action=='quantity_updated'){
echo "<div class='Wow danger'>";
echo "<strong>{$name}</strong> quantity was updated.";
echo "</div>";
}
if(count($_SESSION['cart_items'])>0){
//Gets the Product Id's
$ids = "";
foreach($_SESSION['cart_items'] as $id=>$value){
$ids = $ids . $id . ",";
}
//Removes the comma
$ids = rtrim($ids, ',');
//Starts Table
echo "<table class='table table-hover table-responsive table-bordered'>";
// Table heading
echo "<tr>";
echo "<th class='textAlignLeft'>Product Name</th>";
echo "<th>Price (USD)</th>";
echo "<th>Action</th>";
echo "</tr>";
$query = "SELECT id, name, price FROM products WHERE id IN ({$ids}) ORDER BY name";
$stmt = $con->prepare( $query );
$stmt->execute();
$total_price=0;
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
echo "<tr>";
echo "<td>{$name}</td>";
echo "<td>${$price}</td>";
echo "<td>";
echo "<a href='remove_from_cart.php?id={$id}&name={$name}' class='btn btn-danger'>";
echo "<span class='shopping cart-remove'></span> Remove from cart";
echo "</a>";
echo "</td>";
echo "</tr>";
$total_price+=$price;
}
echo "<tr>";
echo "<td><b>Total</b></td>";
echo "<td>${$total_price}</td>";
echo "<td>";
echo "<a href='#' class='success'>";
echo "<span class='shopping-cart'></span> Checkout";
echo "</a>";
echo "</td>";
echo "</tr>";
echo "</table>";
}
else{
echo "<div class='Wow danger'>";
echo "<strong>No products found</strong> in your cart!";
echo "</div>";
}
include 'layout_foot.php';
?>
What's the real problem here? It's nothing really sophisticated than what you've did before. You'll have some tables like:
offers (id, price, name)
users (id, name)
subscriptions (id, offer_id, user_id, startDate)
Just add a new row in the subscription for each services bought by a user and calcul the sum of his invoice. Then just run a CRON each day for example and send email depending on if the user need to pay his subscription, or not.
Basically I have 4 fields in a form. I want to the user search for books in a library by either title, or by author or both. I also want the user to set the length of the list of items and from the starting point, these are not restrictions though the user does not have to specify.
Here is the code:
require_once __DIR__.'/config.php';
session_start();
$dbh = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_USERNAME, DB_USERNAME, DB_PASSWORD);
$title = $_GET["title"];
$authors = $_GET["authors"];
$st = $_GET["start"];
$ln = $_GET["length"];
$stmt = $dbh->prepare("SELECT title, authors, description, price FROM books WHERE title = :title LIMIT :length OFFSET :start");
$stmt->execute(array(':title' => $title,':start' => $st,':length' => $ln));
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$title = $row['title'];
$authors = $row['authors'];
$description = $row['description'];
$price = $row['price'];
}
echo "<table>";
echo "<tr>";
echo "<td>Title</td>";
echo "<td>$title</td>";
echo "</tr>";
echo "<tr>";
echo "<td>Authors</td>";
echo "<td>$authors</td>";
echo "</tr>";
echo "<tr>";
echo "<td>Description</td>";
echo "<td>$description</td>";
echo "</tr>";
echo "<tr>";
echo "<td>Price</td>";
echo "<td>$price</td>";
echo "</tr>";
echo "</table>";
So far it literally just returns me what I have typed in the input - so nothing much at all! Does anyone know how I can do this?
Adapt your code this way:
echo "<table>";
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$title = $row['title'];
$authors = $row['authors'];
$description = $row['description'];
$price = $row['price'];
echo "<tr>";
echo "<td>Title</td>";
echo "<td>$title</td>";
echo "</tr>";
echo "<tr>";
echo "<td>Authors</td>";
echo "<td>$authors</td>";
echo "</tr>";
echo "<tr>";
echo "<td>Description</td>";
echo "<td>$description</td>";
echo "</tr>";
echo "<tr>";
echo "<td>Price</td>";
echo "<td>$price</td>";
echo "</tr>";
}
echo "</table>";
to print all the rows returned by the query. Your code was printing just the last row.
I have a table in database like this:
ID, features, Values : ID will be 1, 2, 3....
features will be color, size, material....
values will be red, 13inch, silicon...
I stored it like this:
ID
1
1
1
Features
color sizematerial
valuesred13insilicon
and it continues for product 2... . I am trying to display it in tabular form which i am not getting.
Actually it has to go to next row when id -2 comes... but it keeps on displaying in the same row....
can somebody tell me how to do it?
I tried like this
echo "<table width='100%'>";
echo "<tr><th>color</th>
<th>size</th>
<th>material</th></tr>";
echo "<tr>";
while ($row = mysql_fetch_assoc($result)) {
echo "<td>".$row['values']."</td>";
}
echo "</tr>";
echo "</table>";
EDITED **
This is my complete code
if(isset($_POST['submit']))
{
$id = $_POST['id'];
$test = "SELECT id, features, values FROM mytable WHERE features IN ('color', 'size', 'material') AND id IN (" . implode(',',$id) .")";
$result = mysql_query($test) or die (mysql_error());
echo "<table width='100%'>";
echo "<tr><th>color</th>
<th>size</th>
<th>material</th></tr>";
echo "<tr>";
while ($row = mysql_fetch_assoc($result)) {
echo "<td>".$row['values']."</td>";
}
echo "</tr>";
echo "</table>";
}
and the output for print_r(mysql_fetch_assoc($result));
Array ([id] => 1 [features] => color [values] => red )
I think this should solve the problem:
$table_markup = '<tr>';
$current_row = null;
while ( $row = mysql_fetch_assoc($result) ) {
if ( $current_row === null ) {
$current_row = $row['id'];
}
if ( $current_row != $row['id'] ) {
$current_row = $row['id'];
$table_markup .= '</tr><tr>';
}
$table_markup .= '<td>' . $row['values'] . '</td>';
}
/* cutting off the last opened-TR tage */
$table_markup .= substr($table_markup, 0, -4);
echo $table_markup;
I have a myList.php which should list all products added to my favourites and compute the total price of products.
here is the code:
<?php
include 'navigation.php'
?>
<div class='sectionContents'>
<?php
if (isset($_GET['action']) && $_GET['action'] == 'removed') {
echo "<div>" . $_GET['prod_name'] . " was removed from favourites.</div>";
}
if (isset($_SESSION['fav'])) {
$ids = "";
foreach($_SESSION['fav'] as $prod_id) {
$ids = $ids . $prod_id . ",";
}
// remove the last comma
$ids = rtrim($ids, ',');
include "db_connect.php";
$query = mysql_query("SELECT prod_id, prod_name, prod_price FROM tbl_product WHERE prod_id IN ('$ids')") or die(mysql_error());
$num = mysql_num_rows($query);
if ($num > 0) {
echo "<table border='0'>"; //start table
// our table heading
echo "<tr>";
echo "<th class='textAlignLeft'>Product Name</th>";
echo "<th>Price (MUR)</th>";
echo "<th>Action</th>";
echo "</tr>";
//also compute for total price
$totalPrice = 0;
while ($row = mysql_fetch_assoc($query)) {
extract($row);
$totalPrice += $prod_price;
//creating new table row per record
echo "<tr>";
echo "<td>{$prod_name}</td>";
echo "<td class='textAlignRight'>{$prod_price}</td>";
echo "<td class='textAlignCenter'>";
echo "<a href='remove_favourite.php?prod_id= {$prod_id}&prod_name={$prod_name}' class='customButton'>";
echo "<img src='shopping-cart-in-php/images/remove-from- cart.png' title='Remove from favourite' />";
echo "</a>";
echo "</td>";
echo "</tr>";
}
echo "<tr>";
echo "<th class='textAlignCenter'>Total Price</th>";
echo "<th class='textAlignRight'>{$totalPrice}</th>";
echo "<th></th>";
echo "</tr>";
echo "</table>";
echo "<br /><div><a href='#' class='customButton'>Home</a></div>";
} else {
echo "<div>No products found in your favourites. :(</div>";
}
} else {
echo "<div>No products in favourites yet.</div>";
}
?>
I use the add_to_fav.php below to add the products to my favourites:
<?php
session_start();
// get the product id
$prod_id = $_GET['prod_id'];
$prod_name = $_GET['prod_name'];
/*
* check if the 'fav' session array was created
* if it is NOT, create the 'fav' session array
*/
if (!isset($_SESSION['fav'])) {
$_SESSION['fav'] = array();
}
// check if the item is in the array, if it is, do not add
if (in_array($prod_id, $_SESSION['fav'])) {
// redirect to product list and tell the user it was added to favourites
header('Location: prod_list.php?action=exists&prod_id' . $prod_id . '&prod_name=' . $prod_name);
}
// else, add the item to the array
else {
array_push($_SESSION['fav'], $prod_id);
// redirect to product list and tell the user it was added to cart
header('Location: prod_list.php?action=add&prod_id' . $prod_id . '&prod_name=' . $prod_name);
}
?>
I am having "No products found in your favourites. :(" when i try to view the favourites
I have a counter like thing which shows the number of products in my favourites as well and it stays to 0.
Have I erred somewhere? Which mistake should I correct?
There are a few things that could be happening.
1) You are not starting the session before loading the favorites:
<div class='sectionContents'>
<?php
if(isset($_GET['action']) && $_GET['action']=='removed'){
echo "<div>" . $_GET['prod_name'] . " was removed from favourites.</div>";
}
session_start()
if(isset($_SESSION['fav'])){
2) Your SQL query in fact is not finding any product ids. You might want to debug the SQL and run it in phpmyadmin or your mysql interface to see if it in fact does return any results.
include "db_connect.php";
$query = "SELECT prod_id, prod_name, prod_price FROM tbl_product WHERE prod_id IN ('$ids')";
echo $query; // Print query for debugging
$result = mysql_query($query) or die(mysql_error());
$num = mysql_num_rows($result);
My guess is that this query is incorrect because of the single quotes around $ids
It should be:
$query = "SELECT prod_id, prod_name, prod_price FROM tbl_product WHERE prod_id IN ($ids)";
Also this can be simplified from:
$ids = "";
foreach($_SESSION['fav'] as $prod_id){
$ids = $ids . $prod_id . ",";
}
// remove the last comma
$ids = rtrim($ids, ',');
To:
$ids = implode(",", $_SESSION['fav']);