Place a list inside an session and display each session - javascript

Im trying to create a shopping cart style website. I'm able to display the products through setting the products as a class and passing that through to my shopping cart page. However, I need to save the list of products into a session so I can add and or clear each item added to the cart.
Products.php
<?php
require_once 'class_product.php';
$product = new product();
$product_id =(int)$_GET['product_id']; //get id from home page
$username = "";
$password = "";
$hostname = "";//blanked this out for public use
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
//select a database to work with
$selected = mysql_select_db("poti",$dbhandle)
or die("Could not select examples");
//execute the SQL query and return records
$result = mysql_query("SELECT * FROM products where product_id=$product_id");
echo '<form name="form1" method="post" action="cart.php" target="bottom_right">';
echo '<table class="Grocery-table">';
while($row = mysql_fetch_array($result))
{
$product->setProductId($row['product_id']);
$product->setProductName($row['product_name']);
$product->setStock($row['in_stock']);
$product->setUnitPrice($row['unit_price']);
$product->setUnitQuantity($row['unit_quantity']);
}
$_SESSION['product'] = serialize($product);
echo "<tr><td><b>Product ID</b></td>";
echo "<td>";
echo $product->getProductId();
echo "</td></tr>";
echo "<tr><td><b>Product Name</b></td>";
echo "<td>";
echo $product->getProductName();
echo "</td></tr>";
echo "<tr><td><b>Unit Price</b></td>";
echo "<td>";
echo $product->getUnitPrice();
echo "</td></tr>";
echo "<tr><td><b>Unit Quantity</b></td>";
echo "<td>";
echo $product->getUnitQuantity();
echo "</td></tr>";
echo "<tr><td><b>In Stock</b></td>";
echo "<td>";
echo $product->getStock();
echo "</td></tr>";
echo '<tr><td><b>Add</b></td><td><Input type="number" min="0" id="add_value" name="cart"></input>
<Input type="hidden" id="stock_value" name="stock_value" value ='.trim($product->getStock()).'></input></td></tr>';
echo '<tr><td></td><td><input type="submit" value="Submit" onclick="return numCheck()"></td></tr>';
echo "</table>";
echo "</form>";
?>
cart.php
<?php
session_start();
?>
<html>
<style type="text/css">
</style>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>My Grocery Store</title>
</head>
<body>
<h2>Cart</h2>
<?php
require_once 'class_product.php';
$product = unserialize($_SESSION['product']);
//this allows me to see the information when i click submit
echo $product->getProductName();
echo $product->getProductId();
echo $product->getStock();
echo $product->getUnitPrice();
echo $_POST['cart'];
?>
</body>
</html>
How do i place the following $product->getProductName() etc into a Session that enables me to display all the products i've added to my cart.

Try this,
session_start();
$_SESSION['ProductName'] = $product->getProductName();
$_SESSION['ProductId'] = $product->getProductId();
$_SESSION['Stock'] = $product->getStock();
$_SESSION['UnitPrice'] = $product->getUnitPrice();
For multiple products, you may have to use an array of session.
<?php
session_start();
if(!isSet($_SESSION['cart_items']))
{
$_SESSION['cart_items'] = array();
}
$items =$product->getProductName()."|".$product->getProductId()."|".$product-
>getStock()."|".$product->getUnitPrice();
array_push($_SESSION['cart_items'],$items);
echo $_SESSION['cart_items'][0]; //First Product
echo "<br>";
echo $_SESSION['cart_items'][1]; //Second Product
?>

Related

How to keep appending data from database as you retrieve, on a webpage?

Whenever I enter an id number in text box and click scan button, i get data from database and it is displayed below the text box in a predefined format. Now when i enter another id and hit scan, the new data thus retreived replaces the older one. I want it to be displayed below the already existing data on the page.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title> ShopNGo </title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<header id="header">
<div class="container">
<form name="products" method="POST">
<br><br>
<button type="submit" name="scan" id="scan"> <h1> SCAN! </h1> </button>
<br><br><br>
<input type="text" name="id">
</form>
</div>
</header>
<div class="main">
<table border="0">
<?php
if (isset($_POST["scan"])) {
$servername = "localhost";
$username = "#";
$password = "#";
$dbname = "#";
$conn = mysqli_connect($servername, $username, $password, $dbname) or die("Connection Failed:" . mysqli_connect_error());
$query = "SELECT name, price, img FROM product WHERE id = $_POST[id]";
$result = mysqli_query($conn, $query);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
echo "<tr> <table border='0'> <tr>";
echo "<img src='$row[img]'>";
echo "<br>";
echo $row["name"];
echo "<br>";
echo $row["price"];
echo "</tr> </table> </tr>";
}
}
mysqli_close($conn); }
?>
</table>
</div>
</body>
</html>
please help me !!
also it would be a great help if u can suggest some improvements in the existing code other than what i asked for... Thank you so much !!
use ajax to post your id to another php script that checks id for data, put the html into a string variable and then echo it at the end. You can use the ajax success callback to append the data
$.ajax({
type: "POST",
url: url,
data: id,
success: function(data){
$('#targetDiv').append(data);
}
});
php script:
$query = "SELECT name, price, img FROM product WHERE id = $_POST[id]";
$result = mysqli_query($conn, $query);
if(mysqli_num_rows($result) > 0)
{
while($row =
mysqli_fetch_assoc($result))
{
$element = "<tr> <table border='0'> <tr>";
$element .= "<img src='$row[img]'>";
$element .= "<br>";
$element .=$row["name"];
$element .= "<br>";
$element .= $row["price"];
$element .= "</tr> </table> </tr>";
}
}
echo $element;

PHP MySQL Time Attendance - How to limit Time In (Once a day)

I have a Textbox(which is for the Employee ID) and a Time In button that saves the Employee ID, and the current date, and current time(different columns) to the database when clicked. The question is how can I limit the Time in to just once a day.
Here is my code:
<?php
require "sampledb.php";
date_default_timezone_set("Asia/Hong_Kong");
$date = date('Y-m-d');
$time = date('h:i:s');
if(isset($_POST['in'])){
$sql = "INSERT INTO timein(empid, date, time) VALUES(".$_POST['eid'].", '$date', '$time')";
$conn->exec($sql);
if($sql==true){
echo '<script language="javascript">';
echo 'alert("Time in Successful")';
echo '</script>';
echo '<meta http-equiv="refresh" content="0;url=sample.php" />';
}else{
echo "Time in Failed";
}
}
?>
<html>
<head>
</head>
<body>
<form method="POST" action="">
<?php echo date("d/m/y : h:i:sa", time()) . "<br>"; ?>
<input type="text" name="eid" placeholder="Employee ID">
<input type="submit" name="in" value="Time in">
</form>
</body>
</html>
You can add a UNIQUE CONSTRAINT on both the column(empid & date)
Run below query to your table first
ALTER TABLE `timein` ADD UNIQUE `unique_index`(`empid `, `date`);
The combination of empid and date must be unique.
Before doing your sql insert, do a SELECT statement to see if there is a row for that employee in the required date.
If the num_rows is 0 then proceed to INSERT.
If num_rows is not 0 show error alert message.
Try the below in your php.
if(isset($_POST['in'])){
$eid = $_POST['eid'];
$sql = "SELECT empid FROM timein WHERE empid='$eid' AND date='$date'";
$con->exec($sql);
$count = $con->rowCount();
if($count == 0){
$sql = "INSERT INTO timein(empid, date, time) VALUES(".$_POST['eid'].", '$date', '$time')";
$conn->exec($sql);
echo '<script language="javascript">';
echo 'alert("Time in Successful")';
echo '</script>';
echo '<meta http-equiv="refresh" content="0;url=sample.php" />';
} else {
echo "Time in Failed";
}
}

PHP form + select UPDATE to MYSQL table won't Update the row

I have a problem with my update form. When you press the update button it always updates the top row of the table instead of the one you want to update. Using a jquery ajax sendForm function to do the update on the div when you press update. it worked before adding that function.
Trying to update other rows also reverts the change to the top row.
`
foreach ($pdo->query('
SELECT *
from SubPlaceViewer;
')as $row) {
echo "<tr>";
echo "<td>".$row['name']."</td>";
echo "<td>".$row['placeName']."</td>";
echo "<td>".$row['realName']."</td>";
echo "<td>".$row['entID']."</td>";
echo "<td>".$row['firstName']." ".$row['lastName']."</td>";
echo "<td>".$row['length']."</td>";
echo "<td>".$row['height']."</td>";
echo "<td>".$row['fakesnow']."</td>";
?>
<td>/* Changed form-id. Still doesnt d */
<form id="changeSubPlace<?php echo $row['name']; ?>">
<input type="hidden" name="name" value="<?php echo $row['name']; ?>">
<select name='entID'>
<?php
foreach ($pdo->query('SELECT * FROM Ent') as $row) {
echo '<option value="'.$row['entID'].'">';
echo $row['firstName']." ".$row['lastName'];
echo "</option>";
}
?>
</select>
<button type="button" onclick="SendForm('subplace', 'subplace', 'changeSubPlace<?php echo $row['name']; ?>');">update</button>
</form>
</td>
</tr>
<?php
}
?>
</table>
</div>
<?php
if(isset($_POST['name'])){
$sql = "call _newResponsabilitySubPlace (:_entID,:_name)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(":_entID", $_POST['entID'], PDO::PARAM_INT);
$stmt->bindParam(":_name", $_POST['name'], PDO::PARAM_INT);
$stmt->execute();
}
?>`
The function:
function SendForm(page, go, form) {
$.ajax({
url : 'includes/'+page+'.php', // där formulär inmatning hanteras.
type: 'POST',
data: $("#"+form).serialize(), // serializes formulärets element.
success: function(data){
MakeRequest(go); // den div som ska laddas efter körning.
}
});
}

Javascript to php the same file

I have a problem. I need to get the value from a select tag then use it in php for my sql. Here is my code
<div class="form-group">
<label> ROOMS </label>
<?php
echo "<select value= 'TRoom1' id ='TRoom1' class='form control'>";
echo "<option>Select Room Type</option>";
while ($row1 = mysql_fetch_array($result2))
{
echo "<option>" . $row1['Room_type'] . "</option>";
}
echo "</select>";
?>
this is for the sql command
<div class="modal-body">
<div class="container">
<?php
$selectedValue = $_POST['TRoom1'];
$sql = "SELECT RoomNumber FROM rooms Where Room_type = '$selectedValue' ";
$result = mysql_query($sql);
echo "<select value= 'RoomNo' id ='RoomID' class='form-control'>";
echo "<option>Select Room Number</option>";
while ($row = mysql_fetch_array($result))
{
echo "<option>" . $row['RoomNumber'] . "</option>";
}
echo "</select>";
?>
TIA! :))
THis is the code ofor room type with its corresponding room number
<div class="form-group">
<label for="exampleInputEmail1"> ROOMS </label>
<?php
echo "<select value= 'TRoom1' name ='TRoom1' id ='TRoom1' class='form-control'>";
echo "<option>Select Room Type</option>";
while ($row1 = mysql_fetch_array($result2))
{
echo "<option>" . $row1['Room_type'] . "</option>";
}
echo "</select>";
?>
</div>
<div class="form-group">
<?php
$select_value=$_POST['selectedValue'];
$sql = "SELECT RoomNumber FROM rooms Where Room_type = '$select_value' ";
$result = mysql_query($sql);
echo "<select value= 'RoomNo' id ='RoomID' class='form-control'>";
echo "<option>Select Room Number</option>";
while ($row = mysql_fetch_array($result))
{
echo "<option>" . $row['RoomNumber'] . "</option>";
}
echo "</select>";
?>
</div>
you need to use name attribute for your select tag if u want to fetch the value in the php part and in the option u have to pass the value attibute.that value u will get in the php part.
<html>
<head></head>
<body>
<form action="a.php" method="post">
<select name="selectname" id="someid" >
<?php
while ($row1 = mysql_fetch_array($result2))
{
?>
<option value="<?php echo $varible ?>"> <?php echo $row1['Room_type']; ?></option>
<?php } ?>
</select>
<input type="submit" value="submit">
</form>
</body>
</html>
for php part:u can fetch value like this:
filename=a.php
<?php
$select_value=$_REQUEST['selectname'];
$sql1 = "SELECT RoomNumber FROM rooms Where Room_type = '$select_Value' ";
$sql=mysql_result(mysql_query($sql1),0);
?>
Please google your doubts before posting here. There are plenty of example available. mysql_query is deprecated use mysqli_ function
<div class="form-group">
<label> ROOMS </label>
<?php
echo "<select id ='TRoom1' name ='TRoom1' class='form control'>";
echo "<option>Select Room Type</option>";
while ($row1 = mysql_fetch_array($result2))
{
echo "<option value=".$row1['Room_type'].">" . $row1['Room_type'] . "</option>";
}
echo "</select>";
?>
If you are submitting your form as post you would get values as
$sql = "SELECT Room_type, Rate, RoomNumber FROM rooms Where Room_type ='".$_POST['TRoom1']."' ";
Try like
var Sel_val = document.getElementById('TRoom1').value;
Sel_val will be the selected value of that Dropdown.Better you use ajax in your case.If it is on the same page then you use Form submit method.
For the ajax first you need the target url and the value which you want to send..So try like
$.ajax({
url : Url of the page at which the sql command will be there,
type : 'POST',
data : { Sel_val : Sel_val }
});
Then at your target file get the Sel_val via POST method.
I think you used the self action and try this below code
if($_POST){
$selectedValue = $_POST['TRoom1'];
$sql = "SELECT RoomNumber FROM rooms Where Room_type = '$selectedValue' ";
$result = mysql_query($sql);
echo "<select value= 'RoomNo' id ='RoomID' class='form-control'>";
echo "<option>Select Room Number</option>";
while ($row = mysql_fetch_array($result))
{
echo "<option>" . $row['RoomNumber'] . "</option>";
}
echo "</select>";
}

Sequential jquery 'pages', third frame gives a reference error

I am quite new to javascript/jquery and having been playing around with the w3schools tutorials and the jquery documentation and made a page which will accept some user input and then via javascript print some output. I assumed i could modify this to work sequentially but when the second page should call the third page I get
ReferenceError: $gp is not defined
[Break On This Error]
$('#txtField2').load('getglycosites.php?q='+$gp+'r='+$('.glycotype').val());
I would appreciate if anyone has a trick to be able to use the $_get variable in the jquery script.
Code for pages:
first page (test.php):
<html>
<head>
<title>LeidenGlycoPeptide DataBase</title>
<script src="jquery-1.9.1.min.js"></script>
</head>
<script>
$(document).ready(function() {
$('.glycoprotein').change(function() {
$('#txtField').load('getglycopeptides.php?gp='+$('.glycoprotein').val());
});
});
</script>
<body>
<h1>Welcome to the LeidenGlycoPeptide DataBase</h1>
<?php
$link = mysql_connect("localhost","reader","") or die (mysql_error());
mysql_select_db('leidenGlycoPeptide') or die ();
$query = 'select protein from glycoPeptide';
$result = mysql_query($query);
mysql_close($link);
?>
<form>
<p>Select glycopeptide to search for (interactive dialog)</p>
<?php
echo"<select class=\"glycoprotein\">";
echo"<option value=\"\">select glycoprotein</option>";
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
foreach ($line as $col_value) {
echo"<option value=\"$col_value\">$col_value</option>";
}
}
echo"</select>";
?>
</form>
<br>
<div id="txtField"></div>
</body>
</html>
Second Page (getglycopeptides.php):
<html>
<head>
<title>glyco</title>
<script src="jquery-1.9.1.min.js"></script>
</head>
<script>
$(document).ready(function() {
$('.glycotype').change(function() {
//NOTE $q/q are undefined
$('#txtField2').load('getglycosites.php?q='+$gp+'r='+$('.glycotype').val());
});
});
</script>
<body>
<?php
// The next variable is the one I would like to use inside the jquery
$gp=$_GET["gp"];
$link = mysql_connect("localhost","reader","") or die (mysql_error());
mysql_select_db("leidenGlycoPeptide",$link) or die();
$query = "select glycoType from run,glycoPeptide where run.id = glycoPeptide.id and glycoPeptide.protein like '".$gp."'";
$result = mysql_query($query);
?>
<form>
<?php
echo "<select class=\"glycotype\">";
echo "<option value=\"\">select glycosylation</option>";
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
foreach ($row as $col_value)
{
echo"<option value=\"$col_value\">$col_value</option>";
}
}
echo "</select>";
mysql_close($link);
?>
</form>
<br>
<div id="txtField2"></div>
</body>
</html>
The third page (getglycosites.php):
<html>
<head>
<title>sites</title>
</head>
<body>
<?php
$gp=$_GET["gp"];
$r=$_GET["r"];
$link = mysql_connect("localhost","reader","") or die (mysql_error());
mysql_select_db("leidenGlycoPeptide",$link) or die();
$query = "select glycoSite from run,glycoPeptide where run.id = glycoPeptide.id and run.glycoType like '".$r."' and glycoPeptide.protein like '".$q."'";
//echo $query;
$result = mysql_query($query);
echo "<select name=\"site\" onchange=\"foo\">";
echo "<option value=\"\">select glycosite</option>";
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
foreach ($row as $col_value)
{
echo"<option value=\"$col_value\">$col_value</option>";
}
}
echo "</select>";
mysql_close($link);
?>
</body>
</html>
PS: The third page is currently only supposed to show a new select field but once I get this working it will be a part in a large sequential sequence.
Thanks in advance
I was able to 'fix' this by adding the following line (to the jquery script):
var gp = '<?php echo htmlspecialchars($_GET['gp']); ?>';
Making the total script part of the third page:
<script>
var gp = '<?php echo htmlspecialchars($_GET['gp']); ?>';
$(document).ready(function() {
$('.glycotype').change(function() {
$('#txtField2').load('getglycosites.php?q='+gp+'&r='+$('.glycotype').val());
});
});
</script>

Categories