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.
Related
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 . ",";
}
}
Below is the code from catalog page with the data which has to be inserted to the database. It has some problem and i cant insert that data to the database table, and i think i have not ported variables correctly.
My catalogue page has this code (it is for purchasing photographs):
while ($row=mysql_fetch_assoc($result))
{
echo "<tr><td width=100><img src=".$row['FilePath']." /></td>";
echo "<td width=100 padding=25>".$row['Title']."</td>"; $hour = time() + 3600; setcookie('titlecookie', $row['Title'], $hour);
echo "<td width=100 padding=25>".$row['Cost']."</td>";
echo "<td width=100>".$row['FileSize']."</td>";
echo "<td width=100>".$row['CaptureDate']."</td>";
echo "<td width=100>".$row['Resolution']."</td>";
echo "<td width=100><input type=checkbox name=checked[] value=select />Purchase</td></tr>";
}
echo "</table><input type=submit name=submit value=Purchase></form></center>";
}
else
{
echo "Query not successful";
}
The code for my purchase page appears as follows:
$username = "COOKIE['ID_my_site']";
$title = "COOKIE['titlecookie']";
$Custid = mysql_query("SELECT Custid from Customer Where Username=$username");
$Money = $_POST['Cost'];
$Photoid = mysql_query("SELECT Photoid from Photograph Where Title = $row[Title]");
foreach ($_POST['checked'] as $select) {
if(mysql_query('INSERT INTO Transaction (Money, Custid)
VALUES ($Money, $Custid)'))
{
echo "successfully added to Transaction";
}
else
{
echo "Problems adding data to Transaction";
}
if(mysql_query("INSERT INTO TransPhoto (Photoid, Transid)
VALUES ('$Photoid', '$Transid')"))
{
echo "successfully added to Transphoto";
}
else
{
echo "Problems adding data to Transphoto";
}
}
Could you possible assist me with fixing this code? I am relatively new to this but have searched and could not find an effective solution. Thanks
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'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
EDIT
I have a mysql table with fields as follows:
Products - serial, name, description, price, picture.
the viewproducts.php page is as follows:
<?php
$result = mysql_query("SELECT * FROM products ")
or die(mysql_error()); ;
if (mysql_num_rows($result) == 0) {
echo 'There Arent Any Products';
} else {
echo "<table border='0'><table border='1' width=100%><tr><th>Product Name</th><th>Description</th><th>Price</th><th>Image</th><th>Edit</th><th>Delete</th>";
while($info = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $info['name']. "</td>";
echo "<td>" . $info['description']. "</td>";
echo "<td>£" . $info['price']." </td>";
echo "<td>" . "<img src='../getImage.php?id=" . $info['serial'] ."'/></td>";
echo '<td> Edit</td>';
}
}
echo "</tr>";
echo "</table>";
?>
my edit.php page looks like this:
<?php
$product_id = $_GET['serial'];
$result = mysql_query("SELECT * FROM products WHERE serial = '$product_id'")
or die(mysql_error()); ;
if (mysql_num_rows($result) == 0) {
echo 'There Arent Any Products';
} else {
echo "<table border='0'><table border='1' width=100%><tr><th>Product Name</th><th>Description</th><th>Price</th><th>Image</th><th>Edit</th><th>Delete</th>";
while($info = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $info['name']. "</td>";
echo "<td>" . $info['description']. "</td>";
echo "<td>£" . $info['price']." </td>";
echo "<td>" . "<img src='../getImage.php?id=" . $info['serial'] ."'/></td>";
}
}
echo "</tr>";
echo "</table>";
?>
when i click on edit from thr viewproducts.php page, it goes to edit.php page where nothing is showing up. the serial id on the address bar is coming up as follows:
http://www.********.com/****/admin/edit.php?product_id=
I want to be able to edit any product clicked on from the viewproduct.php page and transfered to edit.php page. I dont think my edit.php page is set up corretly.
Please help,
Thanks
You can pass via $_GET the id of the product and then, in the edit/delete page, retrieve that parameter. Obviously you have to sanitize the input properly before using it. For example, the link of the each product should look like this:
echo '<td>Edit</td>';
In the edit page you should have something like:
$id = $_GET['id'];
// For example, if the product id is an integer
// you can sanitize it doing this
$id = (int) $id
You could pass it as an argument to your php file in wich you want to edit/delete the product:
Edit Product
Then in your edit.php you will pick up the id of the product and load it's data from the database.
[edit.php]
$product_id = isset($_GET['product_id']) ? intval($_GET['product_id']) : null;
if(!$product_id) {
exit();
}
// query your database for the product
$row = mysqli_query("SELECT * FROM <table> WHERE product_id = $product_id");
// then you output your html with fields populated from the result from the database