Using Sessions to add items to a cart - php

I have been following a tutorial for a php shopping cart,
I have checked my code over and I am to the point where the add to cart button SHOULD be adding the products into the sidebar.
However, it appears to skip over my if statement and go straight to the else error message stating the product ID is invalid.
I have checked that the SKU in the database match thought that are displayed in $id so i'm a little lost as to why this error persists?
PHP for Products:
<?php
session_start();
if (isset($_GET['action']) && $_GET['action'] == "add") {
$id = $_GET['id'];
if (isset($_SESSION['cart'][$id])) {
$_SESSION['cart'][$id]['quantity']++;
} else {
$sql2 = "SELECT * FROM products WHERE SKU=$id";
$query2 = mysql_query($sql2);
if(mysql_num_rows($query2) != 0){
$row2 = mysql_fetch_array($query2);
$_SESSION['cart'][$row2['SKU']] = array("quantity" => 1, "price" => $row2['price']);
} else {
$message = "This product ID is invalid";
}
}
}
?>
<h2 class="message"><?php if(isset($message)){echo $message;} ?></h2>
<h1>Product Page</h1>
<table>
<tr>
<th>Name</th>
<th>Description</th>
<th>Price</th>
<th>Action</th>
</tr>
<?php
$sql = "SELECT * FROM products ORDER BY SKU ASC";
$query = mysql_query($sql)or die(mysql_error());
while($row = mysql_fetch_assoc($query)){
?>
<tr>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['description']; ?></td>
<td><?php echo "£" . $row['price']; ?></td>
<td>Add to cart</td>
</tr>
<?php
}
?>
PHP for Index.php:
<?php
session_start();
require_once("connect.php");
if (isset($_GET['page'])) {
$pages = array("products","cart");
if (in_array($_GET['page'],$pages)) {
$page = $_GET['page'];
} else {
$page = "products";
}
} else {
$page = "products";
}
?>
<html>
<head>
<link rel="stylesheet" href="reset.css" />
<link rel="stylesheet" href="style.css" />
<title>Shopping Cart - WebThatWorks Ltd</title>
</head>
<body>
<div id="container">
<div id="main"><?php require($page. ".php"); ?></div>
<div id="sidebar">
<h1>Cart</h1>
<?php
if (isset($_SESSION['cart'])) {
$sql = "SELECT * FROM products WHERE SKU IN (";
foreach ($_SESSION['cart'] as $id => $value) {
$sql .=$id. ",";
}
$sql = substr($sql,0,-1) . ")ORDER BY SKU ASC";
$query = mysql_query($sql);
while($row = mysql_fetch_array($query)){
?>
<p><?php echo $row['name']; ?><?php echo $_SESSION['cart'][$row['SKU']]['quantity']; ?></p>
Go To Cart
<?php
}
} else {
echo "<p>Your Cart Is Empty. <br /> Please Add some products</a>";
}
?>
If you require me to post the structure of my database, I shall do so

The problem is your SKU is a string and so it needs quotes in the query:
$sql2 = "SELECT * FROM products WHERE SKU='" . mysql_real_escape_string($id) . "'";
I also added the escape call to prevent SQL Injection, but for best security and other benefits, you should switch to a modern API such as PDO or MySQLi and use prepared statements.
You will also need to make sure the quotes are added to the IN query as well.
foreach ($_SESSION['cart'] as $id => $value) {
$sql .="'" . mysql_real_escape_string($id) . "',";
}

Related

a href background-color change based on field value

I have a field called 'availability' that can be changed between 'Available' and 'UNavailable' for users to choose. If the user is available, I want to have a background of a green color; red is for UNavailable users.
$sql = $db_con->prepare("SELECT * FROM `users` WHERE username = '" . $_SESSION['username'] . "'");
$sql->execute();
while($row = $sql->fetch()){
?>
<tr>
<td>
<?php if ($availability = 'UNavailable') { ?>
<a style="margin:10px;background-color:#FF2828;color:#fff;border-radius:25px;padding:10px;" href="avail/index.php" class="true_home"><?php echo $row['availability']; ?></a></td>
<?php
} else if ($availability = 'Available') { ?>
<a style="margin:10px;background-color:#008000;border-radius:25px;padding:10px;" href="avail/index.php" class="true_home"><?php echo $row['availability']; ?></a></td>
<?php
}
}
?>
Whichever availability status I list first, the color always chooses that one. It ignores the else. I've used else if and just else to see if any changes would occur to allow the value to dictate the background color. Neither have worked.
As always, I truly value everyone's input.
i think this will help you
<style>
.Available {
background-color:#008000;
}
.UNavailable {
background-color:#FF2828;
}
</style>
<?php
$sql = $db_con->prepare("SELECT * FROM `users` WHERE username = '" .
$_SESSION['username'] . "'");
$sql->execute();
while ($row = $sql->fetch())
{ ?>
<tr>
<td>
<a style="margin:10px;border-radius:25px;padding:10px;" href="avail/index.php" class="true_home <?php echo $availability ?>"><?php echo $row['availability']; ?></a>
</td>
</tr><?php
}
?>

I want my button to change the Status set, but instead of changing it, goes to a href page instead

First off: There are no YouTube videos or tutorials for this as far as I know. I found some but they were JavaScript, but I have no knowledge of it so I can't do it in a very short time.
I recently posted the same question but altered my codes after some people's suggestions. I got a lot of errors instead of a solution...
Anyway, I have a picture of my site and what I want to do.
Site:
https://imgur.com/a/hcpuA
and here's a picture of what I want to do:
https://imgur.com/a/Vuuk9
And finally my codes are below, I cut down the HTML parts which isn't really necessary.
adduser.php:
<?php
session_start();
if (!isset($_SESSION['username']))
{
header('location: login.php');
die();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Manage users</title>
<link rel="icon" type="image/png" sizes="16x16" href="image/favicon-16x16.png">
<link rel="icon" type="image/png" sizes="32x32" href="image/favicon-32x32.png">
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" type="text/css" href="css/table.css">
</head>
<body>
<?php include ("header.php"); ?>
<?php
require ("config.php");
?>
<form name="frmSearch" method="post" action="adduser.php">
<div class="table-container">
<div class="table-something">
<div class="table-header">
<span id="message"></span>
<h2>Admin List<span class="blink">_</span> </h2>
<input name="var1" type="text" id="var1" />
<input class="dede" type="submit" name="search" value="search" />
</div>
<div class="table-body">
<table class="table-hen">
<?php
if (isset($_POST['var1'])) {
$var1 = $_POST['var1'];
}
else {
$var1 = 1;
}
$sql= "SELECT user_id, fname, mname, lname, username, type, a_e_num, user_status FROM users WHERE a_e_num LIKE :search";
$stmt = $db->prepare($sql);
$stmt->bindValue(':search', '%' . $var1 . '%', PDO::PARAM_INT);
$stmt->execute();
if ($stmt->rowCount() > 0) {
?>
<tr>
<th>User Id</th>
<th>Name </th>
<th>Username</th>
<th>Employee # </th>
<th>User Type</th>
<th>Status</th>
<th>Action</th>
</tr>
<?php
$result = $stmt->fetchAll();
foreach ($result as $row):
?>
<tr>
<td><?php echo $row['user_id']; ?></td>
<td><?php echo $row['fname']; ?> <?php echo $row['mname']; ?> <?php echo $row['lname']; ?> </td>
<td><?php echo $row['username']; ?></td>
<td><?php echo $row['a_e_num']; ?> </td>
<td><?php echo $row['type']; ?></td>
<td>
<?php if ($row['user_status']=='Enable') echo "Active";
if ($row['user_status']=='Disable') echo "Disabled" ?>
</td>
<td>
<?php
$user_id = $row['user_id'];
$status = '';
if ($row['user_status'] == 'Enable') {
$status = 'Enable';
}
else if ($row['user_status'] == 'Disable') {
$status = 'Disable';
}
?>
<?php
$user_id = $row['user_id'];
$status = $row['user_status'];
?>
<a class="archive" action="archive.php" onclick="
return confirm('Are you sure you want to <?php if ($row['user_status']=='Enable') echo "disable";
if ($row['user_status']=='Disable') echo "enable"?> this user account?')"
href="archive.php?user_id=<?= $user_id?>&status=<?=$status?>">
<?php if ($row['user_status']=='Disable')
echo "Unarchive";
if ($row['user_status']=='Enable')
echo "Archive" ?>
</a></td>
</tr>
<?php endforeach;
} else {
echo 'there is nothing to show';
}
?>
</table>
</form>
</div>
</div>
</div>
<br><h1></h1>
<br><h1></h1>
<br><h1></h1>
<br><h1></h1>
<br><h1></h1>
<?php include ("footer.php"); ?>
</body>
</html>
And here's my Archive.php:
<?php
require ("config.php");
$user_id= $_GET['user_id'];
$user_status = $_GET['user_id'];
$query = $db->prepare ("SELECT * FROM users WHERE user_id = :user_id, user_status = :user_status");
$query->bindParam(':user_id', $user_id);
$query->bindParam(':user_status',$user_status);
$query->execute();
if ($user_status=='Enable')
{
$sql = "UPDATE users SET user_status = 'Disable' WHERE user_id = :user_id";
}
if ($user_status=='Disable')
{
$sql = "UPDATE users SET user_status='Enable' WHERE user_id = :user_id";
}
if ($query->execute([':user_status'=>$user_status, ':user_id'=>$user_id])){
header("Location:adduser.php");
}
?>
First you need to clear your statement and separate your parameters like below.
Step 1:
Parameters are (Query String) which start with ? and more paramters will be followed by &
<?php
$user_id = $row['user_id'];
$status = '';
if ($row['user_status'] == 'Enable') {
$status = 'Enable';
} else if ($row['user_status'] == 'Disable') {
$status = 'Disable';
}
?>
<a href="archive.php?user_id=<?=$user_id?>&user_status=<?=$status?>">
IF your $row['user_status'] value is always same as conditional statement then you don't need condition simply follow assign variable.
<?php
$user_id = $row['user_id'];
$status = $row['user_status'];
?>
<a href="archive.php?user_id=<?=$user_id?>&status=<?=$status?>">
Step 2:
Then this
$id= $_GET['user_id'];
To
$user_id= $_GET['user_id'];
$user_status = $_GET['user_status'];
because your bind parameters take variable which is not defined in your Archive.php
$query->bindParam(':user_id', $user_id);
$query->bindParam(':user_status',$user_status);
EDIT 2:
change your ` where it start with
<td>
<?php
$user_id = $row['user_id'];
$status = $row['user_status'];
Just replace with below.
<td>
<?php
$user_id = $row['user_id'];
$status = $row['user_status'];
$btn_confirm = '';
if ($status == 'Enable') {
$btn_confirm = "disable";
} else if ($status == 'Disable') {
$btn_confirm = "enable";
}
?>
<a class="archive" onclick="return confirm('Are you sure you want to <?= $btn_confirm; ?> this user account?')"
href="Archive.php?user_id=<?= $user_id ?>&status=<?= $status ?>">
<?php if ($status == 'Disable') {
echo "Unarchive";
} else if ($status == 'Enable') {
echo "Archive"; }
?>
</a>
</td>
Note: your file name is Archive.php not archive.php this causing issue for blank page

calling php page from wordpress

I have modified function.php in th wordpress and called php page from the wordpress menu using shortcode. I can able to connect and display php page.
In the php page able to display all the records intially without selecting value from dropdown list. But when I change the value in dropdown list instead of showing the filtered records depending on the dropdown list the page goes to wordpress index page. I suspect onaction command as a submit its not staying in the called php page instead it goes to the wordpress index page.
<?php
$selected = '';
function get_options($select) {
$categories = ['Select Category' => 0, 'Information Technology' => 1, 'Management' => 2];
$options = '';
while (list($k, $v) = each($categories)) {
if ($select == $v) {
$options .= '<option value="' . $v . '" selected>' . $k . '</option>';
} else {
$options .= '<option value="' . $v . '" >' . $k . '</option>';
}
}
//var_dump($options);
//echo var_dump($options)."<br>";
return $options;
}
require_once('dbconnect.php');
if (isset($_POST['categories'])) {
$selected = $_POST['categories'];
echo $selected;
}
if ($selected == 1) {
$selectedcat = 'Information Technology';
$selectsql = "SELECT * FROM courses where ccategory='$selectedcat'";
} else if ($selected == 2) {
$selectedcat = 'Management';
$selectsql = "SELECT * FROM courses where ccategory='$selectedcat'";
} else {
$selectsql = "SELECT * FROM courses";
}
//require_once('dbconnect.php');
//include('header-basic-light.php');
//$selectsql="SELECT * FROM courses";
$res = (mysqli_query($con, $selectsql));
if (!mysqli_query($con, $selectsql)) {
die(mysqli_error($con));
}
mysqli_close($con);
//header('Location:index.php');
?>
<HTML>
<head>
//<title>"View Information"</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<label for="categories">Select the Category : </label>
<select name="categories" style="width:250px;" onchange="this.form.submit();">
<?php echo get_options($selected); ?>
</select>
</form>
<h2>View Information</h2>
<table class="table">
<tr>
<th>#</th>
<th>cname</th>
<th>start_date</th>
<th>duration</th>
<th>Remarks</th>
<th>Options</th>
</tr>
<?php
while ($r = mysqli_fetch_assoc($res)) {
?>
<tr>
<td><?php echo $r['cno']; ?></td>
<td><?php echo $r['cname']; ?></td>
<td><?php echo $r['start_date']; ?></td>
<td><?php echo $r['duration']; ?></td>
<td><?php echo $r['remarks']; ?></td>
<?php if ($r['ccategory'] == 'Information Technology') {
$catnum = 1;
}
if ($r['ccategory'] == 'Management') {
$catnum = 2;
} ?>
<td>Details&nbsp&nbsp
</tr>
<?php } ?>
</table>
</body>
</html>
The usage of a short code is a requirement? Why not creating a page-slug.php, override it via a child theme and getting redirections and urls via standard permalink function?

List box shows blank line space below each element

Listbox shows blank line space below each element. Increased the width also but still the blank line appears. I have attached the screenshot for reference.I have attached the code file. I am using a function to select the records from the dropdown list . The dropdown list is working but blank record shows below every value which is shown in the screenshot.
<?php
$selected = '';
function get_options($select) {
$categories = array('Information Technology' => 1, 'Management' => 2);
$options = '';
while (list($k, $v) = each($categories)) {
if ($select == $v) {
$options .= '<option value="' . $v . '" selected>' . $k . '<option>';
} else {
$options .= '<option value="' . $v . '" >' . $k . '<option>';
}
}
return $options;
}
require_once('dbconnect.php');
if (isset($_POST['categories'])) {
$selected = $_POST['categories'];
echo $selected;
}
if ($selected == 1) {
$selectedcat = 'Information Technology';
$selectsql = "SELECT * FROM courses where ccategory='$selectedcat'";
} else
if ($selected == 2) {
$selectedcat = 'Management';
$selectsql = "SELECT * FROM courses where ccategory='$selectedcat'";
} else {
$selectsql = "SELECT * FROM courses";
}
//require_once('dbconnect.php');
include('header-basic-light.php');
//$selectsql="SELECT * FROM courses";
$res = (mysqli_query($con, $selectsql));
if (!mysqli_query($con, $selectsql)) {
die(mysqli_error($con));
}
mysqli_close($con);
//header('Location:index.php');
?>
<HTML>
<head>
<title>"View Information"</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<label for="categories">Select the Category : </label>
<select name="categories" style="width:250px;" onchange="this.form.submit();">
<?php echo get_options($selected); ?>
</select>
</form>
<h2>View Information</h2>
<table class="table">
<tr>
<th>#</th>
<th>cname</th>
<th>start_date</th>
<th>duration</th>
<th>Remarks</th>
<th>Options</th>
</tr>
<?php
while ($r = mysqli_fetch_assoc($res)) {
?>
<tr>
<td><?php echo $r['cno']; ?></td>
<td><?php echo $r['cname']; ?></td>
<td><?php echo $r['start_date']; ?></td>
<td><?php echo $r['duration']; ?></td>
<td><?php echo $r['remarks']; ?></td>
<?php
if ($r['ccategory'] == 'Information Technology') {
$catnum = 1;
}
if ($r['ccategory'] == 'Management') {
$catnum = 2;
}
?>
<td>Details&nbsp&nbsp
</tr>
<?php
}
?>
</table>
</body>
</html>
Listbox screenshot
1st : You missed forward slash in option close tag </option>
$options.='<option value="'.$v.'" selected>'.$k.'</option>';
2nd : Try to use prepared statement to avoid sql injection .

applying search or filter to table with pagination

hello kind sirs can you help me with this code. What i try to do is when i type something in the search box, ex. pending it will show the 5 pending reservation per page(5 rows of pending reservation). but when i try it, it shows all the pending reservation which is more than 10.
here is the image
i try something like this.. but it shows nothing
$query = "SELECT * FROM reservations WHERE CONCAT(firstname, lastname, reservationstatus)LIKE '%".$valueToSearch."%' LIMIT " . $this_page_first_result . ',' . $results_per_page";
Here is the whole code
<?php
error_reporting(E_ALL & ~E_NOTICE);
error_reporting(E_ERROR | E_PARSE);
session_start();
?>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "srdatabase";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$results_per_page = 5;
$select= "SELECT * FROM reservations";
$result = mysqli_query($conn, $select);
$number_of_results = mysqli_num_rows($result);
if(!isset($_GET['page']))
{
$page = 1;
}
else
{
$page = $_GET['page'];
}
$this_page_first_result = ($page-1)*$results_per_page;
$sql = "SELECT * FROM reservations LIMIT " . $this_page_first_result . ',' . $results_per_page;
$result = mysqli_query($conn, $sql);
$number_of_pages = ceil($number_of_results/$results_per_page);
?>
<div id="paging-div">
<?php
for($page=1;$page<=$number_of_pages;$page++)
{
echo '<a id="pagingLink" href="adminControl.php?page=' . $page . '">' . $page . '</a>';
}
?>
<?php
if(isset($_POST['search']))
{
$valueToSearch = $_POST['valueToSearch'];
$query = "SELECT * FROM reservations WHERE CONCAT(firstname, lastname, reservationstatus)LIKE '%".$valueToSearch."%'";
$search_result = filterTable($query);
}
else
{
$query = "SELECT * FROM reservations";
$search_result = filterTable($query);
}
function filterTable($query)
{
$conn = mysqli_connect("localhost", "root", "", "srdatabase");
$filter_Result = mysqli_query($conn, $query);
return $filter_Result;
}
?>
</div>
<!DOCTYPE html>
<html>
<head>
<title>Admin Control</title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<div class="topnav" id="myTopnav">
Home
Speakers
About
Contact
Reservation
Sign Out
<?php echo $_SESSION['firstname']; ?>
Sign Up
Sign In
Admin control
☰
</div>
<br>
<br>
<br>
<br>
<h4 style="padding-left:10px; text-align:center;">Reservation List</h4>
<hr>
<form action="adminControl.php" method="POST">
<input type="text" name="valueToSearch" placeholder="type a value">
<input type="submit" name="search" value="Filter">
</form>
<br>
<br>
<div style="overflow-x:auto;">
<table class="reservations-table">
<tr>
<th class="thFirstName">First Name</th>
<th class="thLastName">Last Name</th>
<th class="thEmailAddress">Email Address</th>
<th class="thContactNumber">Contact Number</th>
<th class="thSpeaker">Speaker</th>
<th class="thTopic">Topic</th>
<th class="thLocation">Location</th>
<th class="thAudience">Audience</th>
<th class="thCount">Count</th>
<th class="thTime">Time</th>
<th class="thDate">Date</th>
<th class="thAction">Reservation Date</th>
<th class="thAction">Status</th>
<th class="thAction">Action</th>
<th class="thAction">Action</th>
</tr>
<?php while($row = mysqli_fetch_array($search_result)):?>
<tr>
<td><?php echo $row['firstname'];?></td>
<td><?php echo $row['lastname'];?></td>
<td><?php echo $row['emailaddress'];?></td>
<td><?php echo $row['contactnumber'];?></td>
<td><?php echo $row['speaker'];?></td>
<td><?php echo $row['topic'];?></td>
<td><?php echo $row['location'];?></td>
<td><?php echo $row['audience'];?></td>
<td><?php echo $row['count'];?></td>
<td><?php echo $row['time'];?></td>
<td><?php echo $row['date'];?></td>
<td><?php echo $row['reservationdate'];?></td>
<td><?php echo $row['reservationstatus'];?></td>
</tr>
<?php endwhile;?>
</table>
</form>
</div>
<?php
$epr='';
$msg='';
if(isset($_GET['epr']))
$epr=$_GET['epr'];
if($epr=='delete')
{
$id=$_GET['id'];
$delete=mysqli_query($conn, "DELETE FROM reservations WHERE id=$id");
if($delete)
header('location:adminControl.php');
else
$msg='Error :'.mysqli_error();
}
?>
<?php
$epr='';
$msg='';
if(isset($_GET['epr']))
$epr=$_GET['epr'];
if($epr=='approve')
{
$id=$_GET['id'];
$approve=mysqli_query($conn, "UPDATE reservations SET reservationstatus='approved' WHERE id=$id");
header('location:adminControl.php');
}
?>
<script>
function myFunction() {
var x = document.getElementById("myTopnav");
if (x.className === "topnav") {
x.className += " responsive";
} else {
x.className = "topnav";
}
}
</script>
<script>
function ifAdmin()
{
document.getElementById("signIn").style.display = "none";
document.getElementById("signUp").style.display = "none";
document.getElementById("signOut").style.display = "block";
document.getElementById("adminControl").style.display = "block";
}
</script>
<script>
function ifNotAdmin()
{
document.getElementById("signIn").style.display = "none";
document.getElementById("signUp").style.display = "none";
document.getElementById("signOut").style.display = "block";
document.getElementById("adminControl").style.display = "none";
}
</script>
<script>
function ifNotLogin()
{
document.getElementById("user").style.display = "none";
document.getElementById("signOut").style.display = "none";
document.getElementById("adminControl").style.display = "none";
}
</script>
<?php
if (isset($_SESSION['signedIn']) && $_SESSION['signedIn'] == true)
//if login
{
if($_SESSION['type'] == 1)
{
echo "<script type='text/javascript'>ifAdmin();</script>";
}
elseif($_SESSION['type'] == 0)
{
echo "<script type='text/javascript'>ifNotAdmin();</script>";
}
}
//if not login
else
{
echo "<script type='text/javascript'>ifNotLogin();</script>";
}
?>
<div id="footer" class="push">Copyright 2017</div>
</body>
</html>
... when i try it, it shows all the pending reservation which is more than 10.
That's because when you hit 2nd, 3rd, ... pages(after navigating from the 1st page), the $_POST array would be empty i.e. $_POST['search'] won't be set, and that's why else{...} part of the code will get executed every time you navigate to 2nd, 3rd, ... pages. Since you're not sending any sensitive data with the form, use GET instead of POST in the method attribute of the form, like this:
<form action="..." method="get">
and get the user inputted data like this:
if (isset($_GET['search'])) {
$valueToSearch = $_GET['valueToSearch'];
...
Subsequently, you need to attach that search query in each of your pagination links, so that the search query would be available when you hop from page to page.
// your code
<?php
for($page=1;$page<=$number_of_pages;$page++)
{
echo "<a id='pagingLink' href='adminControl.php?page=" . $page . "&valueToSearch=". urlencode($_GET['valueToSearch']) ."&search'>" . $page . "</a>";
}
?>
// your code

Categories