I am developing a shopping cart system and everything is working perfectly, except for one thing.
Well, I use PHP SESSION to store the data for each product, including ID, name, price and quantity. All variables are correctly completed, unless the price variable. I do not know why! I use jQuery to fetch the values and send them to the page that will process them in the SESSION.I will put the relevant parts of my code to facilitate. This is the content of my products.php:
<?php
session_start();
?>
<html>
<body>
<?php
$connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$sql = "SELECT id, name, price FROM products ORDER BY id";
$result = $connection->query($sql);
if ($result->num_rows > 0)
{
echo "<table>";
echo " <tr>";
echo " <th>ID</th>";
echo " <th>NAME</th>";
echo " <th>PRICE</th>";
echo " <th>QUANTITY</th>";
echo " </tr>";
while($row = $result->fetch_assoc())
{
echo " <tr>";
echo " <td><div class='id-product'>". $row["id"]."</div></td>";
echo " <td><div class='name-product'>". $row["name"]."</div></td>";
echo " <td>$<div class='price-product'>". $row["price"]."</div></td>";
echo " <form class='add'>";
echo " <td><input type='number' name='quantity' value='1' min='1'/></td>";
echo " <td><button type='submit'>Add</button></td>";
echo " </form>";
echo " </tr>";
}
echo "</table>";
}
$connection->close();
?>
<script>
$(document).ready(function()
{
$('.add').on('submit', function()
{
var id = $(this).closest('tr').find('.id-product').text();
var name = $(this).closest('tr').find('.name-product').text();
var price = $(this).closest('tr').find('.price-product').val();
var quantity = $(this).closest('tr').find('input').val();
window.location.href = "add.php?id=" + id + "&name=" + name + "&price=" + price + "&quantity=" + quantity;
return false;
});
});
</script>
<body>
</html>
Now in add.php I have the following:
<?php
session_start();
$id = isset($_GET['id']) ? $_GET['id'] : "";
$name = isset($_GET['name']) ? $_GET['name'] : "";
$price = isset($_GET['price']) ? $_GET['price'] : "";
$quantity = isset($_GET['quantity']) ? $_GET['quantity'] : "";
$cart_item = array
(
'id' => $id,
'name' => $name,
'price' => $price,
'quantity' => $quantity
);
if(!isset($_SESSION['cart']))
{
$_SESSION['cart'] = array();
}
if(array_key_exists($id, $_SESSION['cart']))
{
header('Location: products.php?action=exists&id=' . $id . '&name=' . $name);
}
else if($quantity <= 0)
{
header('Location: products.php?action=invalidquantity&id=' . $id . '&name=' . $name);
}
else
{
$_SESSION['cart'][$id] = $cart_item;
header('Location: products.php?action=added&id=' . $id . '&name=' . $name);
}
?>
To show the products that exists in the SESSION, I use foreach in my page cart.php:
$total = 0;
foreach($_SESSION['cart'] as $id)
{
echo "<tr>";
echo "<td>{$id['name']}</td>";
echo "<td>${$id['price']}</td>";
echo "<td>{$id['quantity']}</td>";
echo "<td>";
echo "<a href='remove.php?id={$id['id']}&name={$id['name']}'>Remove</a>";
echo "</td>";
echo "</tr>";
$total += ($id['price'] * $id['quantity']);
}
As I said earlier, I have returned the values of ID, name and quantity, but the price remains empty. What's wrong?
You're not setting the price right in your JS i believe.
window.location.href = "add.php?id=" + id + "&name=" + name + "&price" + price + "&quantity=" + quantity;
return false;
Should be
window.location.href = "add.php?id=" + id + "&name=" + name + "&price=" + price + "&quantity=" + quantity;
return false;
See difference in jquery's .val and .text
Difference between val() and text()
try this:
var price = $(this).closest('tr').find('.price-product').text();
Related
When I click on Add to cart hyperlink, cart.php page is not responding (it's not echoing the add variable. Hyperlink looks fine. However, there is something wrong in cart.php. Any response is appreciated. Thanks in advance.
<html>
<head>
</head>
<body>
<table>
<tr>
<td><?php echo $row['ISBN']; ?></td>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['title']; ?></td>
<td><?php echo $row['year']; ?></td>
<td><?php echo $row['price']; ?></td>
<td><?php echo $row['publisher']; ?></td>
<td> Add to cart</td>
<td><?php echo $row['ISBN']; ?></td>
</tr>
</table>
</body>
</html>
cart.php page:
<?php
//
session_start();
$page = 'search.php';
$lpage = 'cart.php';
$db = new mysqli('localhost', 'root', '', 'cheapbook') or die('Error connecting to MySQL server.');
mysqli_set_charset($db, 'utf8');
if (isset($_GET['add'])) {
echo $_GET['add'];
$pieces = explode(":", $_GET['add']);
$quantity = mysqli_query('SELECT ISBN, title from book WHERE ISBN=$pieces[0]');
$result = mysqli_query($db, $quantity);
while ($quantity_row = mysqli_fetch_array($result)) {
if ($quantity_row['quantity'] != $_SESSION['cart_' . $_GET['add']]) {
$_SESSION['cart_' . $_GET['add']] += 1;
}
}
if ($pieces[1] == 'SearchByBookTitle') {
header('location:' . $page . 'SearchByBookTitle=' . $pieces[2]);
}
if ($pieces[1] == 'SearchByAuthor') {
header('location:' . $page . 'SearchByAuthor=' . $pieces[2]);
echo $pieces[1];
} else {
header('location:' . $lpage);
}
}
if (isset($_GET['remove'])) {
$_SESSION['cart_' . $_GET['remove']]--;
header('location:' . $page);
}
if (isset($_GET['delete'])) {
$_SESSION['cart_' . $_GET['remove']]--;
header('location:' . $page);
}
if (isset($_GET['cart'])) {
cart();
}
function cart()
{
foreach ($_SESSION as $name => $value) {
if ($value > 0) {
if (substr($name, 0, 5) == 'curt_') {
$total = 0;
$id = substr($name, 5, (strlen($name) - 5));
$get = mysql_query("SELECT ISBN, title, price FROM book where id='.$id.'");
$result = mysqli_query($db, $get);
while ($get_row = mysqli_fetch_array($result)) {
$sub = $get_row['price'] * $value;
echo $get_row['title'] . 'X' . $value . '#Dollar' . $get_row['price'] . '=' . $sub . '[-][+][Delete]';
}
$total += $sub;
}
}
if ($total == 0) {
echo "Your cart is empty";
} else {
echo "Paypal button";
}
}
}
?>
This query coded like this of course will not work as expected
$quantity = mysqli_query('SELECT ISBN, title
from book
WHERE ISBN=$pieces[0]');
You need a double quoted string to use variable expansion, it does not work in a single quoted string.
You also need to add single quotes around the text varibale parameter value
$quantity = mysqli_query("SELECT ISBN, title
from book
WHERE ISBN='$pieces[0]'");
In future you would be well advised to add some error checking code after you attempt to execute a query and also use prepared and parameterised queries to avoid SQL Injection
$sql = "SELECT ISBN, title from book WHERE ISBN=?";
$stmt = mysqli_prepare($sql);
if ( ! $stmt ) {
echo mysqli_error();
exit;
}
$stmt->bind_param('s', $pieces[0] );
$stmt->execute();
I have recently changed servers and things arent working like they did before
I have pin pointed that the session information is not tranferring from one page to the next
this is half of the first page
<?php include 'header.php';?>
<?php
session_start();
$id = isset($_GET['id']) ? $_GET['id'] : "";
$con = mysqli_connect("*","*","*","*");
// SELECT DATABASE
$db = mysqli_select_db("images", $con);
function GetCartId()
{
// This function will generate an encrypted string and
// will set it as a cookie using set_cookie. This will
// also be used as the cookieId field in the cart table
if(isset($_COOKIE["cartId"]))
{
return $_COOKIE["cartId"];
}
else
{
// There is no cookie set. We will set the cookie
// and return the value of the users session ID
setcookie("cartId", session_id(), time() + ((3600 * 24) * 30));
return session_id();
}
}
// Get data from the database depending on the value of the id in the URL
$id = $_GET["id"];
$strSQL = "SELECT * FROM images WHERE image= '$id'";
$rs = mysqli_query($con,$strSQL);
while($row = mysqli_fetch_array($rs)) {
$name = $row['image_name'];
echo '<h1 style="font-size:2em;">';
echo $name;
echo'</h1>';
echo '<div id = "galpic">';
$thispic = $row['image'];
echo '<div id = "pic">';
echo '<br /> <img src="'.$thispic.'" style = "max-width:100%;"/> ';
echo '</div>';
$description = $row['image_description'];
echo ' <h3>about</h3>';
echo ' <h3>card</h3>';
echo ' <h3>small</h3>';
echo ' <h3>big</h3>';
echo ' <h3>limited</h3>';
echo ' <h3>share</h3>';
echo '</div>';
}
$_SESSION['name'] = $name;
$_SESSION['thispic'] = $thispic;
THESE LAST TWO LINES ARE THE SESSION INFORMATION THAT WORKS FOR THE REST OF THIS PAGE BUT DOES NOT PASS THROUGH TO THE NEXT PAGE
then the next page is............
<?php include 'header.php';?>
<?PHP
session_start();
$con = mysqli_connect("*","*","*","*");
$_SESSION['name'] = '$name';
$_SESSION['thispic'] = '$thispic';
echo '<div id = "foodbowl">';
echo '<h1>ORDER FORM</h1>';
echo '</div>';
echo '<div id = "checkout">';
echo '<table style = "font-size:0.7em;margin-top:3%;line-height:100%;">';
echo '<tr>';
echo '<td>checkout progress bar:</td>';
echo '<td>check your order</td>';
echo '<td style = "background-color:#e8d9d9">fill in details</td>';
echo '<td>choose payment option</td>';
echo '<td>final check?</td>';
echo '</tr>';
echo '</table>';
echo '</div>';
function GetCartId()
{
// This function will generate an encrypted string and
// will set it as a cookie using set_cookie. This will
// also be used as the cookieId field in the cart table
if(isset($_COOKIE["cartId"]))
{
return $_COOKIE["cartId"];
}
else
{
// There is no cookie set. We will set the cookie
// and return the value of the users session ID
setcookie("cartId", session_id(), time() + ((3600 * 24) * 30));
return session_id();
}
}
$checkout = mysqli_query($con,"SELECT * FROM cart where cookieId = '".GetCartId()."'");
echo '<div id = "checkout">';
echo '<table>
<tr>
<th colspan = "4"><b>YOUR CHOICE</b></th>
<th><b>PRICE</b></th>
</tr>
';
while ($row = mysqli_fetch_array($checkout)){
$pic = $row['image'];
echo '<tr><td>';
echo $row['name'];
echo '</td><td>';
echo '<img src="'.$pic.'" style ="height:33px;"/>' ;
echo '</td><td >';
echo $row['product'];
echo '</td><td >';
echo '$'. $row['price'].'.00 au';
echo '</td></tr>';
}
echo '<tr><td colspan ="4">';
echo '<p>TOTAL</P>';
echo '</td><td>';
$result = mysqli_query($con,"select sum(price) as total from cart where cookieId = '".GetCartId()."'");
while($row = mysqli_fetch_assoc($result)){
echo '$'.$row['total'].'.00 au';
}
echo '</td></tr>';
echo '</table>';
echo '</div>';
$name = $row['name'];
$product = $row['product'];
?>
<form id="buyer" method="post" action="email.php" >
<p> these are the details Mandy will need to send your product -</p>
<?php
$checkout = mysqli_query($con,"SELECT * FROM cart where cookieId = '".GetCartId()."'");
while ($row = mysqli_fetch_array($checkout)){
echo '<br / >';
echo 'a '.$row['product'];
echo ' of '.$row['name'];
}
?>
You cannot have any - any - output before you call session_start(). That includes the blank line between ?> and <?php, as well as anything in header.php. When you do have output, it prevents you from sending a session cookie with session_start(). No cookie, no session.
Put session_start() at the very top of your scripts and don't open and close PHP tags (<?php ... ?>) without reason.
I have the code below and am trying to get the next 25 results from my sql table to appear on page. However, whenever I click the next button, no information is displayed. I have my offset = ($page - 1) * $items_per_page......I'm struggling to figure this out as it seems so simple compared the other code I've written, but is proving to be very elusive to me....any assistance would be greatly appreciated. My primary issue is that the next link does not provide the next 25 results and I'm unable to determine why and how to correct.
echo "<h3 style='text-align:center;'>Welcome to the Exchange Portal, " . $row['name'] . "! </h3>";
$items_per_page = 25;
$sql_count = "SELECT pin, title, title2, email, phone FROM crown_acura";
$result_cnt = mysqli_query($conn, $sql_count);
if(false === $result_cnt) {
throw new Exception('Query failed with: ' . mysqli_error());
} else {
$row_count = mysqli_num_rows($result_cnt);
// free the result set as you don't need it anymore
//mysqli_free_result($result_cnt);
}
echo $row_count;
echo " ";
if (!isset($_GET['Page'])) {
$Page = 1;
} else {
$Page = $_GET['Page'];
}
echo $page;
echo " ";
$page_count = 0;
if (0 === $row_count) {
// maybe show some error since there is nothing in your table
} else {
// determine page_count
$page_count = (int)ceil($row_count / $items_per_page);
// double check that request page is in range
if($page > $page_count) {
// error to user, maybe set page to 1
$page = 1;
}
}
echo " ";
echo $page_count;
echo " ";
echo $items_per_page;
$offset = ($page-1)*$items_per_page;
//echo $paging_info;
//echo " ";
echo "<br />";
//Query for displaying results
$list_sql = "SELECT pin, title, title2, email, phone FROM crown_acura LIMIT $offset, $items_per_page";
$result_query = $conn->query($list_sql);
//Table for displaying query results
echo "<table class='verify'>";
echo "<tr >";
echo "<td><h3>Name</h3></td><td> </td><td><h3>E-mail</h3></td><td><h3>Phone</h3></td>";
echo "</tr>";
for($i = 1; $i<= $page_count; $i++) {
if ($result_query->num_rows > 0) {
// output data of each row
while($row3 = mysqli_fetch_array($result_query)) {
echo "<tr>";
echo "<td class='dltd2 dlcl'>" . $row3["title"] . "</td><td>" . $row3["title2"] . "</td><td><a href='mailto:" . $row3['email'] . "'>" . $row3["email"] . "</a> </td><td>" . $row3["phone"] . " </td>";
echo "</tr>";
}
} else {
echo "0 results";
}
}
echo "<tr></tr>";
$next_page = $page + 1;
$last_page = $page - 1;
if($paging_info['curr_page'] <= 1) {
echo "<tr>";
echo "<td></td><td colspan='2'><a class='loadlink' href='" . $_PHP_SELF . "'>Next 25</a></td><td></td>";
echo "</tr>";
} elseif ($paging_info['curr_page'] < $page_count) {
echo "<tr>";
echo "<td></td><td><a href='" . $_PHP_SELF . "?page=" . $last_page . "'>Prev 25</a></td><td><a href='" . $_PHP_SELF . "?page=" . $next_page . "'>Next 25</a></td><td></td>";
echo "</tr>";
} elseif ($paging_info['curr_page'] === $page_count) {
echo "<tr>";
echo "<td></td><td colspan='2'><a href='" . $_PHP_SELF . "?page=" . $last_page . "'>Prev 25</a></td><td></td>";
echo "</tr>";
}
echo "</table>";
}
}
}
Have you tried to run the rendered SQL.
Output to browser:
"SELECT pin, title, title2, email, phone FROM crown_acura LIMIT $offset, $items_per_page"
try this... and change $page for different values (2,3,...,etc)
<?php
$items_per_page = 25;
$sql_count = "SELECT pin, title, title2, email, phone FROM crown_acura";
$result_cnt = mysqli_query($conn, $sql_count);
if (false === $result_cnt) {
throw new Exception('Query failed with: ' . mysqli_error());
} else {
$row_count = mysqli_num_rows($result_cnt);
// free the result set as you don't need it anymore
//mysqli_free_result($result_cnt);
}
echo $row_count;
echo " ";
if (!isset($_GET['Page'])) {
$Page = 1;
} else {
$Page = $_GET['Page'];
}
echo $page;
echo " ";
$page_count = 0;
if (0 === $row_count) {
// maybe show some error since there is nothing in your table
} else {
// determine page_count
$page_count = (int)ceil($row_count / $items_per_page);
// double check that request page is in range
if ($page > $page_count) {
// error to user, maybe set page to 1
$page = 1;
}
}
echo " ";
echo $page_count;
echo " ";
echo $items_per_page;
$offset = ($page - 1) * $items_per_page;
//echo $paging_info;
//echo " ";
echo "<br />";
//Query for displaying results
$list_sql = "SELECT pin, title, title2, email, phone FROM crown_acura LIMIT $offset, $items_per_page";
$result_query = $conn->query($list_sql);
echo ("RESULTS: ".$result_query->num_rows());
?>
I have a fully working pagination with get method. I get the results from my query and the page is changed when the variable pagination changes on URL. I recently changed the site to ajax and now I can't get the clicked page value from URL
I have a form with some inputs that I use to generate the query and a ajax structure that connects to the PHP file and put the result on a div
My php file:
//items per page
$quantidade = 30;
//actual page
$pagina = (isset($_GET['pagina'])) ? (int)$_GET['pagina'] : 1;
$inicio = ($quantidade * $pagina) - $quantidade;
$sql .= " LIMIT " . $inicio . " , " . $quantidade ;
$qr = mysql_query($sql) or die(mysql_error());
echo "<table id='tab_vendas' border='1' width='100%'>";
echo "<tr><td>Data</td><td>Loja</td><td>Total (AKZ)</td><td>Total (USD)</td><td>Multicaixa</td><td>Saidas</td><td>Visa</td></tr>";
$num_rows = mysql_num_rows($qr);
if($num_rows > 0){
while($ln = mysql_fetch_assoc($qr)){
echo "<tr><td>" . $ln['data']."</td>";
echo "<td>" . $ln['loja']."</td>";
echo "<td>" . $ln['totalkz']."</td>";
echo "<td>" . $ln['totaldollar']."</td>";
echo "<td>" . $ln['multicaixa']."</td>";
echo "<td>" . $ln['saidas']."</td>";
echo "<td>" . $ln['visa']."</td></tr>";
}
}else{
echo "Não foram encontrados registos";
}
echo"</table></div>";
//total
$sqlTotal = "SELECT id FROM vendas";
$qrTotal = mysql_query($sqlTotal) or die(mysql_error());
$numTotal = mysql_num_rows($qrTotal);
$totalPagina= ceil($numTotal/$quantidade);
$exibir = 3;
$anterior = (($pagina - 1) == 0) ? 1 : $pagina - 1;
$posterior = (($pagina+1) >= $totalPagina) ? $totalPagina : $pagina+1;
echo "<div id='paginacao'><a href='?pagina=1'>Primeira</a> | ";
echo "<< | ";
for($i = $pagina-$exibir; $i <= $pagina-1; $i++){
if($i > 0)
echo ' '.$i.' ';
}
echo '<strong>['.$pagina.']</strong>';
for($i = $pagina+1; $i < $pagina+$exibir; $i++){
if($i <= $totalPagina)
echo ' '.$i.' ';
}
echo " | >> | ";
echo " Ultima</div>";
My big question is how can I get the actual page value and how to know what button the user clicked.
I tried to change the link's to a submit button with form attribute that send the form again and run all code again but I can't figured out how to pass the clicked button value.
echo " | <input type='submit' form='filtros' name='$posterior' value='>>'>";
echo " <input type='submit' form='filtros' name='$totalPagina' value='Ultima'></div>";
You can simply modify your code to make this work as it was when the pages where links.
<a class="page" href="url.com?parameter=value¶meter2=value2">pageNumber</a>
javscript code is:
$('.a.page').on('click', function() {
var url = $(this).attr(href);
$.ajax({
type: 'GET',
url: url,
success: function(response) {
$('selector to the container you wish to put the data').html(response.data)
}
});
})
In your php yous should echo json_encode your data
echo json_encode(array('data' => $data));
I have three php scripts. main.php questions.php and values.php
Here's the code
main.php
<html>
<head>
<title></title>
</head>
<body>
<h1>Be Prepare for the battle</h1>
<?php
$strTitle = "Begin";
$strLink = "<a href = 'question.php?ques_id=1'>" . $strTitle ."</a>";
echo $strLink;
?>
</body>
</html>
questions.php
<?php
require_once('../connect.php');
$quesSQL = mysql_query("SELECT * FROM `questions` WHERE `ques_id`=". $_GET["ques_id"]);
if(!mysql_num_rows($quesSQL) >= 1)
{
die('Complete.');
}
$next = $_GET["ques_id"];
while($row = mysql_fetch_array($quesSQL)) {
$id = $row['ques_id'];
$strTitle = $row['ques_title'];
echo "<li>" . $strTitle . "</li><br/>";
}
$optSQL = mysql_query("SELECT `options`,`values` FROM questions_options WHERE " . $id . "= ques_id");
echo "<form action=\"values.php\" method=\"POST\">";
while($row = mysql_fetch_array($optSQL) ) {
$strOptions = $row['options'];
$strValues = $row['values'];
echo "<input type =\"radio\" name =\"valueIn\" value=" . $strValues . " />" . $strOptions . "<br/>";
}
echo "</form>";
$strTitle = "<input type =\"submit\" value=\"Next\">";
$next = $next + 1;
$strLink = "<a href = 'values.php?ques_id=" . $next . "'>" . $strTitle ."</a>";
echo $strLink;
mysql_close();
?>
values.php
<?php
require_once('../connect.php');
$input = $_POST['valueIn'];
$ansSQL = mysql_query("SELECT `answer` FROM questions WHERE 1-".$_GET["ques_id"]."= ques_id");
$marks = 0;
if($input == $ansSQL)
{
$marks = $marks+1;
}
else
{
$marks = $marks+0;
}
echo $marks;
?>
Now problem is i have to pass one value from second script(questions.php) to third script(values.php).
And it is from the <form> section in radio button's name value "valueIn". But I can't do that. Because I'm sending another value ques_id with $strLink variable at the end of the second script.
So how can i do that?
I'm not sure why your using a link to handle what should probably be in the form. As stated by anusha you should be using a hidden input field for ques_id like so
questions.php
<?php
require_once('../connect.php');
$quesSQL = mysql_query("SELECT * FROM `questions` WHERE `ques_id`=". $_GET["ques_id"]);
if(!mysql_num_rows($quesSQL) >= 1)
{
die('Complete.');
}
$next = $_GET["ques_id"];
while($row = mysql_fetch_array($quesSQL)) {
$id = $row['ques_id'];
$strTitle = $row['ques_title'];
echo "<li>" . $strTitle . "</li><br/>";
}
$optSQL = mysql_query("SELECT `options`,`values` FROM questions_options WHERE " . $id . "= ques_id");
echo "<form action=\"values.php\" method=\"POST\">";
while($row = mysql_fetch_array($optSQL) ) {
$strOptions = $row['options'];
$strValues = $row['values'];
echo "<input type =\"radio\" name =\"valueIn\" value=" . $strValues . " />" . $strOptions . "<br/>";
}
$next = $next + 1;
$strLink = '<input type="hidden" name="ques_id" value="'.$next.'">';
echo $strLink;
$strTitle = "<input type =\"submit\" value=\"Next\">";
echo $strTitle;
echo "</form>";
mysql_close();
?>
Both variables when then be available via $_POST on the next step like below
$input = $_POST['valueIn'];
$ques_id = $_POST['ques_id'];
You can use hidden input like Mike's answer, or you can still use GET parameter like this:
questions.php
<?php
// .........
// .........
// .........
// .........
// add / change your code for this part
$next = (int) $next;
$optSQL = mysql_query("SELECT `options`,`values` FROM questions_options WHERE ques_id = " . $next);
echo '<form action="values.php?ques_id=' . ($next+1) . '" method="POST">';
while($row = mysql_fetch_array($optSQL) ) {
$strOptions = $row['options'];
$strValues = $row['values'];
echo '<input type="radio" name ="valueIn" value="' . $strValues . '" />' . $strOptions . '<br/>';
}
echo '<input type="submit" value="Next">';
echo "</form>";
mysql_close();
// end change
?>
values.php
<?php
// add / change your code for this part
$_GET["ques_id"] = (int) $_GET["ques_id"];
$ansSQL = mysql_query("SELECT `answer` FROM questions WHERE ques_id = " . ($_GET["ques_id"]-1));
// end change
// .........
// .........
// .........
// .........
You can add multiple parameters with 'a' tag.
Like
"<a href = 'values.php?ques_id=".$next." & ques_id1=1'>" . $strTitle ."</a>"
You can also use a hidden input field for variable $question_id and submit the form