I'm working on my homework. I have a cart session and I can get on the attribute in mySql database base on the product id.
<?php
$total_price=0;
if(isset($_SESSION['cart']) ? $_SESSION['cart'] : null)
{
echo "<tr>
<th></th>
<th>Product</th>
<th>Price</th>
<th>Quantity</th>
</tr>";
foreach ($_SESSION['cart'] as $key => $product) {
$the_query = "SELECT * FROM products WHERE id=" . $product->id;
$the_product = $db->query($the_query) or die('Query failed: '.mysql_error());
$the_product->execute();
$the_product->setFetchMode(PDO::FETCH_OBJ);
while ($row = $the_product->fetch()){
$total_price = $total_price + $row->price*$product->quantity;
echo "<tr><td>";
echo "<img src='".$row->image_url_small."' /></a></td>";
echo "<td><strong>".$row->name."</strong></td><td><em>$".$row->price."</em>";
echo '</td>';
echo '<td><input type="text" id="'.$row->id.'" class="override" value="'.$product->quantity.'"/></td>';
echo '<td>Delete item </td></tr>';
}}
echo "<tr><td colspan='2'></td></tr>";
echo "<tr><td style='text-align:center;font-size:40px;'>$</td><td><strong>Total</strong><br /><em>$".$total_price."</em></td></tr>";
}
else {
echo "Your cart is empty.";
}
?>
Update
I can pass the id to do_deletecart.php. But now I can delete the product from cart
do_deletecart.php
<?php
session_start();
$product = $_GET['id'];
foreach($_SESSION['cart'] as $key=>$value) {
if($product == $value)
{
unset($_SESSION['cart'][$key]);
break;
} }
header("location:cart.php");
?>
Well, assuming that $row->id contains what you expect, you have enclosed it with quote marks, which will essentially terminate the <a> element's href attribute.
You need to update your code as follows:
echo '<td>Delete item </td></tr>';
Also, you might want to check that you have actually started the session. In order to access the $_SESSION superglobal, you need to first have called session_start() before any output was sent to the browser.
You need to make sure you include
session_start(); before using $_SESSION
Related
In our website, we have textbox to ask input values from user. If user input the data Q54497899, rest of the results must be shown from database. Rightnow, I want to add checkbox on each result. I tried to add with foreach but it still doesn't work for me. I will provide codes below which were written in the correlationwafer_result.php. Want to add checkbox beside each Q54497899
<?php
// ini_set("memory_limit","512M");
include("_dbconn.php");
include("//sgewsnant21.amk.st.com/ewsweb/wwwroot/library/common7/db_config.inc");
include("//sgewsnant21.amk.st.com/ewsweb/wwwroot/library/common7/standard_defines.inc");
session_start();
$productlotid = isset ($_GET['productlotid'])? $_GET['productlotid']:'';
$sql = "SELECT * FROM productdb.tbl_correlationwafer WHERE `lotid` = '$productlotid'";
$result1 = mysqli_query($conn,$sql);
$cnt = 0;
echo "<table id='corwafer'>";
while ($row = mysqli_fetch_assoc($result1)) {
echo "<tr>";
echo "<th colspan='2'>Lot ID:</th>";
echo "<th colspan='2'>Product:</th>";
echo "<th colspan='4'>EWSFLOW </th>";
echo "<th>Zone</th>";
echo "</tr>";
$field1name = $row["lotid"];
$field2name = $row["product"];
$field3name = $row["ewsflow"];
$field4name = $row["zone"];
echo '<tr>
<td colspan="2">'.$field1name.'</td>
<td colspan="2">'.$field2name.'</td>
<td colspan="4">'.$field3name.'</td>
<td >'.$field4name.'</td>
</tr>';
foreach($productlotid as $k => $v){
if($k == $row["lotid"]){
echo "<input type=\"checkbox\" id=\"chkproductlotid" . $cnt . "\" name=\"chkproductlotid\" value=\"$v\"><font face=\"arial\" size=\"2\" color=\"#3C5F84\">". $k . "</font>";
}
}
$cnt++;
}
echo "</table>";
flush();
mysqli_close($conn);
?>
Try :
$('chkproductlotid').val();
$productlotid = isset ($_GET['productlotid'])? $_GET['productlotid']:'';
Your $productlotid is more like a string not an array, does it?
You should put your checkbox inside td, and I think your checkbox value should be able to take from the first While Loop, no need that Foreach..
I have a table in database and I want to fetch the data from it. I know how to fetch data from database using php. But the problem is that
this table is different in structure. For example
and so on...
As you can see this table is like a pivot table. That is the real problem for me. All the entries of a single person should be in single row. But it is in different rows and single column (all entries of single person is in value column).
I have tried to fetch table with regular way like this
<?php
/*
Template Name: Registration
*/
get_header();
$results = $wpdb->get_results( "SELECT * FROM wp_cf_form_entry_values", ARRAY_A );
$count = $results->num_rows;
if(!empty($results)) {
echo "<table width='100%' border='1' cellspacing='1'>";
echo "<tbody>";
foreach($results as $row){
echo "<tr>";
echo "<td><center>" . $row['value'] . "</center></td>";
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
} else {
echo "<table width='100%' border='1' cellspacing='1'><tr><td>No Records Found</td></tr></table>";
}
get_footer();?>
But with the above code it's showing all the results in a single column and that's what I expect from above code.
So I don't know the correct code to represent this table as single row entries of single person. I searched a lot but didn't get much.
I'm pretty sure you looking for something like this:
horizontal representation: (by Person)
<?php
/*
Template Name: Registration
*/
get_header();
global $wpdb;
//Create a mulit dimensional array for each person.
$persons = array();
$fields = $wpdb->get_results( 'SELECT * FROM wp_cf_form_entry_values');
foreach($fields as $field){
$persons[$field->entry_id][$field->slug] = $field->value;
}
//the table
echo '<table width="100%" border="1" cellspacing="1">';
$i=0;
foreach($persons as $id=>$values){
//the table header (only in the first loop)
if($i==0){
echo '<tr>';
foreach($values as $key=>$val){
echo '<th>'.$key.'</th>';
}
echo '</tr>';
}
// one line per person
echo '<tr id="'.$id.'">';
foreach($values as $key=>$val){
echo '<td>'.$val.'</td>';
}
echo '</tr>';
$i++;
}
if($i==0){
echo "<table width='100%' border='1' cellspacing='1'><tr><td>No Records Found</td></tr></table>";
}
echo '</table>';
get_footer();?>
vertical representation (by field slug)
<?php
/*
Template Name: Registration
*/
get_header();
global $wpdb;
//Create a mulit dimensional array for each slug.
$field_slugs = array();
$fields = $wpdb->get_results( 'SELECT * FROM wp_cf_form_entry_values');
foreach($fields as $field){
$field_slugs[$field->slug][$field->entry_id] = $field->value;
}
//the table
echo '<table width="100%" border="1" cellspacing="1">';
$i=0;
foreach($field_slugs as $slug=>$values){
//the table header (only in the first loop)
if($i==0){
echo '<tr>';
foreach($values as $person_id=>$val){
echo '<th></th>';
echo '<th>Person '.$person_id.'</th>';
}
echo '</tr>';
}
// one line per person
echo '<tr id="'.$slug.'">';
echo '<td><b>'.$slug.'</b></td>';
foreach($values as $person_id=>$val){
echo '<td>'.$val.'</td>';
}
echo '</tr>';
$i++;
}
if($i==0){
echo "<table width='100%' border='1' cellspacing='1'><tr><td>No Records Found</td></tr></table>";
}
echo '</table>';
get_footer();?>
You use foreign key entries_id so you can retrieve from that table ie
$results=$wpdb->get_results("select * from entries_table");
foreach($results as $result){
$entries_id=$result->id;
$entry_detail=$wpdb->get_results(SELECT * from form_field_table where entries_id='$entries_id' ");
foreach($entry_detail as $ent_detail){?>
<td><?php echo $ent_detial->slug;?></td><td><?php echo $ent_detial->value;?></td>
<?php }
}
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.
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']);
I have a following question. I store a shopping cart in an array session like below
session_start();
$id= $_GET['id'];
if(isset($_SESSION['cart']))
{
array_push($_SESSION['cart'], $id);
}
else
$_SESSION['cart']= array($id);
header("location:cart.php");
And when I try to retrieve the cart. I get the same product id as many as I put to the cart.
<?php
if(!isset($_SESSION['cart'])) {
echo "Your cart is empty.<br /><br /><a href='products.php'>Show products</a>";
} else {
echo '<table border="0.2">';
$total_price = 0;
foreach($_SESSION['cart'] as $id) {
$the_query = "select * from products where id='$id' GROUP BY id";
$result = mysql_query($the_query) or die('Query failed: ' . mysql_error());
$the_product = mysql_fetch_array($result, MYSQL_ASSOC);
$total_price = $total_price + $the_product['price'];
$href = "show_products.php?id=".$the_product['id'];
//echo "<tr>";
echo "<tr><td><a href='$href'>";
echo "<img src='".$the_product['image_url_small']."' /></a></td>";
echo "<td><strong>".$the_product['name']."</strong></td><td><em>$".$the_product['price']."</em>";
echo "</td>";
echo "<td> <a href='do_deletecart.php?id=". $the_product['id'] ."'>Delete item </a></td></tr>";
}
echo "<tr><td colspan='2'></td></tr>";
echo "<tr><td style='text-align:center;font-size:40px;'>$</td><td><strong>Total</strong><br /><em>$".$total_price."</em></td></tr>";
echo "</table>";
echo "<br /><a href='empty_cart.php'>Empty Cart</a> <a href='showallproducts.php'>Show phones</a><br /><br />";
}
how can I make it show only one product id or name. Thank in advance
If I understand your question correctly, you are getting many results for the same product id. This is because you are storing same id values many time in the $_SESSION variable.
You could do the following to not repeat the same ids in the $_SESSION variable.
EDIT
For sake of completeness I have updated the code. Hope that helps.
index.php
<?php
session_start();
$id= isset($_GET['id']) ? $_GET['id'] : null;
if(!is_null($id)){
if(isset($_SESSION['cart']) && count($_SESSION['cart']) > 0){
// increment product quantity if already exists
// or create a new one
add_or_increment_product_to_cart($id, $_SESSION['cart']);
} else {
// initialize cart
// add the first product
$_SESSION['cart'] = array();
array_push($_SESSION['cart'], (object) array('id' => $id, 'quantity' => 1));
}
}
function add_or_increment_product_to_cart($id, $cart){
foreach ($cart as $key => $product) {
if($id == $product->id){
$product->quantity++;
return;
}
}
array_push($_SESSION['cart'], (object) array('id' => $id, 'quantity' => 1));
}
header("location:cart.php");
Cart.php
<?php
session_start();
$cart = isset($_SESSION['cart']) ? $_SESSION['cart'] : null;
if($cart) {
foreach ($cart as $key => $product) {
$the_query = "SELECT * FROM products WHERE id=" . $product->id . " LIMIT 1";
// your code to fetch the products from the database
// what you have done is fine but vulnerable
// PDO recommended
}
} else {
echo "Your cart is empty.<br /><br /><a href='products.php'>Show products</a>";
}
Also please note that mysql_connect is deprecated and PDO class is the recommended and safe way to connect to the database. Your code is vulnerable to SQL Injection like #Touki said in his comment.
I would recommend performing only one query to retrieve all of the products, and then iterate the result of the query to populate the HTML. For example;
$the_query = "select * from products where id in (". implode(',', $_SESSION['cart']) .")";
$result = mysql_query($the_query);
while (($the_product = mysql_fetch_array($result, MYSQL_ASSOC))) {
...
}
This has the added bonus that you only perform one query, and would also only select one row per product.
It's worth noting, however, that the mysql_* methods are deprecated, and it would be advisable to start using another library such as mysqli or PDO.
On a related note, this code currently is very liable to SQL injection, and the input should ideally be sanitised before being put into a query string.