The sessions between multiple pages on my site is not persisting. This it the session code I have at the start of each page:
<?php
#session_start();
echo session_id();
?>
I then add the variables to the session:
$_SESSION["CustomerID"]= $IDCustomer;
$_SESSION["PaymentID"]= $IDPayment;
var dumping this directly afterwards shows the correct variable. however, when doing the exact same on the next page, the variables are NULL. The only thing I have done between var dumping the variables on the first page, and var dumping them on the second page is clicking the hyperlink to switch the pages.
This is the code in full for each page:
<?php
require_once("php/init.php");
echo session_id();
$Cat = $_GET['Type'];
//create an instance of the ADO connection object
$conn = new COM ("ADODB.Connection")
or die("Cannot start ADO");
//show the connection string
$connStr = "PROVIDER=Microsoft.ACE.OLEDB.12.0;Data Source= \www\DMG Games Website\DMG Database.accdb";
$conn->open($connStr); //Open the connection to the database
//Read customer + payment from $Get
//Store in session variables
$IDCustomer = $_GET['CustomersDropdown'];
$IDPayment = $_GET['PaymentsDropdown'];
$_SESSION["CustomerID"]= $IDCustomer;
$_SESSION["PaymentID"]= $IDPayment;
//create the Products query
$query = "SELECT * FROM [Product Details]";
if (isset($Cat)) {
$query = "SELECT * FROM [Product Details] Where [Product Type] ='" . $Cat . "'";
}
//execute query
$rs = $conn->execute($query);
//count the number of columns
$num_columns = $rs->Fields->Count();
echo "There are " . $num_columns . " columns." . "<br>";
for ($i=0; $i < $num_columns; $i++) {
$fld[$i] = $rs->Fields($i);
}
//show the information in a table
echo "<table>";
echo "<tr>";
echo "<th> Product ID </th>";
echo "<th> Product Name </th>";
echo "<th> Product Description </th>";
echo "<th> Price </th>";
echo "<th> Quantity In Stock </th>";
echo "<th> Product Type </th>";
echo "<th> Image </th>";
echo "<th> Click to Buy </th>";
echo "</tr>";
while (!$rs->EOF) //carry on looping while there are records to be obtained
{
echo "<tr>";
for ($i=0; $i < $num_columns; $i++) {
echo "<td>" . $fld[$i]->value . "</td>";
}
echo "</tr>";
$rs->MoveNext(); //move on to the next record
}
echo "</table>";
//close the connection
$rs->Close();
$conn->Close();
$rs = null;
$conn = null;
$Customer = $_SESSION["CustomerID"];
var_dump($Customer);
$Payment = $_SESSION["PaymentID"];
var_dump($Payment)
?>
This is the code for the second page:
//create an instance of the ADO connection object
$conn = new COM ("ADODB.Connection")
or die("Cannot start ADO");
//show the connection string
$connStr = "PROVIDER=Microsoft.ACE.OLEDB.12.0;Data Source= \www\DMG Games Website\DMG Database.accdb";
$conn->open($connStr); //Open the connection to the database
// Get the url variables
$Pid = $_GET['newPid'];
// Read the quantity from the address
$Quantity = $_GET['newQuantity'];
//Create a query for retreiving the product image
$queryGetImage = "SELECT [Image] FROM [Product Details] Where [Product ID]=" . $Pid;
//execute the query
$rs = $conn->execute($queryGetImage);
echo "<h2> Add product to basket </h2>";
echo "</br></br>";
echo $rs->Fields("Image");
echo "</br></br>";
//declare the form
?>
<FORM NAME ="QuantityForm" METHOD ="get" ACTION = "">
Product ID:</br> <INPUT TYPE = "TEXT" NAME ="newPid" VALUE = "<?php echo $Pid;?>">
</br></br>
Quantity:</br> <INPUT TYPE = "TEXT" NAME ="newQuantity">
</br></br>
<input type="submit" />
</form>
<?php
//Create the AddToBasket query
if (isset($Quantity)) {
// Add the product and the quantity to the basket table
$AddtoBasketQuery = "INSERT INTO Basket([Product ID], [Quantity])
VALUES ('$Pid', '$Quantity')";
//execute the query
$conn->execute($AddtoBasketQuery);
//close the connection
$conn->Close();
$conn = null;
echo "</br> Your product has succesfully been added to your basket.";
}
?>
I don't see
session_start();
on your second script, you need to put it at the top of each script which wants to use session variables
You need to add session_start(); at start in second script. To access the Session variables this is required to start session before doing anything.
Related
I have two PHP files: itemTransaction.php and recordItemTransaction.php. I can select which row I would like to record a transaction for from a table in itemTransaction, and it links to the correct row in the database in recordItemTransaction.php, leading to a form allowing me to edit the itemQuantity. I have a form that has a hidden ID field and a textbox for the user to enter in an updated itemQuantity, which will be submitted to the database upon submission. I would like to display the current itemQuantity to the user, so when they edit the itemQuantity, they know what the current quantity is before they edit it and record the transaction.
My issue is that in recordItemTransaction.php, I cannot figure out how to pull in both the values for ID and itemQuantity in the same file.
This links to recordItemTransaction.php. Since I am referencing ID here, I can retrieve it in the next file. But I cannot retrieve itemQuantity along with the ID. Only one or the other. So, when I switch it to...
...I can retrieve the itemQuantity value in the textbox, but when I submit the form, it cannot tell which row to update.
itemTransaction.php
$query = "SELECT * FROM `Items` WHERE `isActive` = 'Active'";
$result = mysqli_query($con, $query);
echo "<h1>Record Transaction | Items</h1>";
echo "<a href='../inventoryIndex.php'><button class='button'>Back</button></a>";
//Display Data
echo "<table class='applyFont' cellspacing='0' cellpadding='0'>";
echo "<tr>";
echo "<th></th>";
echo "<th>ITEM</th>";
echo "<th>COST</th>";
echo "<th>RECORD TRANSACTION</th>";
echo "</tr>";
while($row=mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td align='center' width='9%'><img src='/InventoryManager/InventoryManagerImages/Items/{$row['itemImage']}' width='115' height='125' style='display:block'></td>";
echo "<td align='center' width='30%'>{$row['description']}</td>";
echo "<td align='center' width='30%'>$ {$row['unitCost']}</td>";
echo "<td align='center'><a href='recordItemTransaction.php?ID={$row['ID']}'><img src='/InventoryManager/InventoryManagerImages/Icons/couple-of-arrows-changing-places.png' title='Record an update to inventory'></td>";
echo "</tr>";
}
?>
</body>
</html>
recordItemTransaction.php
>
>
<?php
if(isset($_POST['updateQuantity'])) {
//Connect to DB
$hostname = "******";
$username = "******";
$password = "******";
$dbName = "******";
$con = mysqli_connect($hostname, $username, $password, $dbName);
//Get Value From User
$itemQuantity = $_POST["itemQuantity"];
$ID = $_POST["ID"];
//Query to Update Data
$query = "UPDATE `Items` SET `itemQuantity`='$itemQuantity' WHERE ID='$ID'";
$result = mysqli_query($con, $query);
//Check if Query Was Successful
if($result) {
echo "<p style=font-family:'Roboto Condensed', sans-serif>Item quantity has been updated</p>";
} else {;
echo "<p style=font-family:'Roboto Condensed', sans-serif>Error updating the quantity of the item.</p>" . mysqli_error();
}
//Disconnect From DB
mysqli_close($con);
}
?>
<body>
</body>
</html>
First of all, i am sorry if this question has been asked before.I am working on a shopping cart. My current code will only show 1 item in the cart. It means that when i click add to cart on #product1 it will show me #product1 detail in the cart. However when i click add to cart for #product2, it will override the information of #product1.
Here is my code for product:
<div >
<image src="ip5s.jpg">
<p><font color="blue">  Iphone 5S</font></p>
<p><font color="red">  RM1999</font></p>
<p><form name="addcart" method="post" action="processcart.php">
<input type="submit" name="addtocart" value="Add to cart">
<input type="hidden" name="product_id" value="1234" />
<input type="hidden" name="quantity" value="1" />
</form>
</p>
</div>
Here is the code for process.php:
<?php
session_start();
include_once("config.php");
$pid=$_POST['product_id'];
$_SESSION['product'] = array($pid);
sleep(2);
echo "Add to cart successful";
header("refresh:1;url=cart.php");
exit();
?>
Here is the code for cart.php:
<?php
if(!isset($_SESSION['cart']))
echo "<p>Your shopping cart is empty!</p>";
else{
$tblname="products";
require_once("dbcon.php");
$proids = array();
foreach($_SESSION['product'] as $id)
{
$proids[] = $id;
}
$proids = implode(',', $proids);
$query = "SELECT * from $tblname where product_id in ('$proids') ";
$result = mysql_query($query) or die(mysql_error());
echo "<table>";
while($row = mysql_fetch_array($result,MYSQL_ASSOC)){
echo "<tr><td>" . $row[$i]['product_name'] . "</td><td>" . $row[$i]['product_price'] . "</td></tr>" ;
}
echo "</table>";
mysql_free_result($result);
mysql_close();
}
Add session_start() to the beginning of cart.php to resume the session.
Also, in order to add multiple product IDs to the $_SESSION['product'] variable, which is probably what you'll be doing, you'll have to change
$_SESSION['product'] = array($pid);
to
$_SESSION['product'][] = $pid;
Which inserts $pid to the end of $_SESSION['product'] array.
USE array_push() .make an array with card Ids and display them using forloop
<?php
session_start();
include_once("config.php");
$pid = $_POST['product_id'];
$_SESSION['product'] = array();
$_SESSION['product'] = array_push($_SESSION['product'], $pid);
sleep(2);
echo "Add to cart successful";
header("refresh:1;url=cart.php");
exit();
?>
Try
<?php
session_start();
if(isset($_SESSION['quantity']))
$_SESSION['quantity']=$_SESSION['quantity']+1;
else
$_SESSION['quantity']=1;
echo "Cart=". $_SESSION['quantity'];
?>
As you seem to be really stuck on this:
process_cart.php
<?php
session_start();
include_once("config.php");
// test & generate cart if needed
if(! isset($_SESSION['cart']))
{
$_SESSION['cart'] = array("products"=>array());
}
// add current product
// ! note: you need to add data validation to this to avoid SQL injects
$_SESSION['products'][$_POST['product_id']] = $_POST['quantity'];
// Show you have done something
sleep(2);
echo "Add to cart successful";
header("refresh:1;url=cart.php");
exit();
?>
databaseConnection.php
<?php
define("DB_HOST", "localhost");
define("DB_NAME", "onlinestore");
define("DB_USER", "root");
define("DB_PASSWORD", "");
mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
mysql_select_db(DB_NAME);
?>
cart.php:
<?php
session_start();
if (!isset($_SESSION['cart']))
{
// No items yet added to the cart
echo "<p>Your shopping cart is empty!</p>";
}
else
{
// set table
$tblname = "products";
// get connection
require_once('DatabaseConnection.php');
// create a list with product ID's
$prodids = array();
// For each product in the cart
foreach($_SESSION['cart']['products'] as $id => $qntity)
{
// add id to the array
$prodids[] = $id;
}
// combine into a string
$prodids = implode(',', $prodids);
$query = "SELECT * from $tblname where product_id in ($prodids) ";
// (The query should really be mysqli)
$result = mysql_query($query) or die(mysql_error());
echo "<table>";
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo "<tr><td>" . $row['product_name'] . "</td><td>" . $row['product_price'] . "</td></tr>". $_SESSION['cart']['products'][$row['product_id']];
}
echo "</table>";
mysql_free_result($result);
mysql_close();
?>
Back with another quick question. I have this code below which echo's out product names from a database. What I want to do is make the echoed out product names a link to another page called product.php, each link needs to have a unique ID, for example
Product Name
How would I go about doing this? Many thanks. I will point out that I am very new to PHP.
<?php
//create an ADO connection and open the database
$conn = new COM("ADODB.Connection");
$conn->open("PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=C:\WebData\Northwind.mdb");
//execute an SQL statement and return a recordset
$rs = $conn->execute("SELECT product_name FROM Products");
$num_columns = $rs->Fields->Count();
echo "<table border='1'>";
echo "<tr><th>Name</th></tr>";
while (!$rs->EOF) //looping through the recordset (until End Of File)
{
echo "<tr>";
for ($i=0; $i < $num_columns; $i++) {
echo "<td>" . $rs->Fields($i)->value . "</td>";
}
echo "</tr>";
$rs->MoveNext();
}
echo "</table>";
//close the recordset and the database connection
$rs->close();
$rs = null;
$conn->close();
$conn = null;
?>
Assuming your Products table has a unique ID field called "id", change your select to:
$rs = $conn->execute("SELECT id, product_name FROM Products");
And when you want to create a link, use that field and pass it into the URL. So you'd have product.php?id=<?= $thatIdField; ?>.
Example code:
echo "<table border='1'>";
echo "<tr><th>Name</th></tr>";
while (!$rs->EOF) //looping through the recordset (until End Of File)
{
echo "<tr>";
for ($i=0; $i < $num_columns; $i++) {
echo "<td>" . $rs->Fields($i)->value . "</td>";
}
echo "</tr>";
$rs->MoveNext();
}
echo "</table>";
Purpose: To update an inventory database by using the onchange function by modifying the data displayed in a PHP table.
I am pulling my data from a database and displaying it in a table. I have the data displayed in text fields so they are editable. Once the data is edited my function uses the data provided by POST, preferably the item ID and the value, will be used to update the inventory.
Here is my 'inventory.php' code:
$db = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$inventory = mysqli_query($db, "SELECT item_id, item_name, item_quantity, item_cost, item_price FROM inventory");
$num_rows = mysqli_num_rows($inventory);
mysqli_close($db);
echo "<form id=\"update_add_inventory\" action=\"\" method=\"post\">";
echo "<table>";
echo "<tr>";
echo "<th>Item ID</th>";
echo "<th>Item Name</th>";
echo "<th>Item Quantity</th>";
echo "<th>Item Cost</th>";
echo "<th>Item Price</th>";
echo "</tr>";
$i = 1;
while($row = mysqli_fetch_array($inventory))
{
echo "<tr>";
echo "<td>".$row['item_id']."</td>";
echo "<td><input type=\"text\" name=\"item_".$i."_name\" onchange=\"updateInventory('update_inventory.php')\" value='".$row['item_name']."' /></td>";
echo "<td><input type=\"text\" name=\"item_".$i."_quantity\" onchange=\"updateInventory('update_inventory.php')\" value='".$row['item_quantity']."' /></td>";
echo "<td><input type=\"text\" name=\"item_".$i."_cost\" onchange=\"updateInventory('update_inventory.php')\" value='".$row['item_cost']."' /></td>";
echo "<td><input type=\"text\" name=\"item_".$i."_price\" onchange=\"updateInventory('update_inventory.php')\" value='".$row['item_price']."' /></td>";
echo "</td></tr>";
$i++;
}
echo "</table><br>";
echo "</form>";
Here is my 'onchange function':
function updateInventory(action)
{
document.getElementById('update_add_inventory').action = action;
document.getElementById('update_add_inventory').submit();
}
Here is my 'update_inventory.php' code:
$db = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$inventory = mysqli_query($db, "SELECT item_id, item_name, item_quantity, item_cost, item_price FROM inventory");
$num_rows = mysqli_num_rows($inventory);
$i = 1;
for ($n=1; $n<=$num_rows; $n++) {
if (isset($_POST['item_'.$i.'_name'])) {
$item_id = $_POST['item_'.$i.'_id'];
$item_name = $_POST['item_'.$i.'_name'];
$result = mysqli_query($db, "UPDATE inventory SET item_name='".$item_name."' WHERE item_id='".$item_id."'");
} else if (isset($_POST['item_'.$i.'_quantity'])) {
$item_id = $_POST['item_'.$i.'_id'];
$item_name = $_POST['item_'.$i.'_quantity'];
$result = mysqli_query($db, "UPDATE inventory SET item_quantity='".$item_quantity."' WHERE item_id='".$item_id."'");
} else if (isset($_POST['item_'.$i.'_cost'])) {
$item_id = $_POST['item_'.$i.'_id'];
$item_name = $_POST['item_'.$i.'_cost'];
$result = mysqli_query($db, "UPDATE inventory SET item_cost='".$item_cost."' WHERE item_id='".$item_id."'");
} else if (isset($_POST['item_'.$i.'_price'])) {
$item_id = $_POST['item_'.$i.'_id'];
$item_name = $_POST['item_'.$i.'_price'];
$result = mysqli_query($db, "UPDATE inventory SET item_price='".$item_price."' WHERE item_id='".$item_id."'");
}
$i++;
}
mysqli_close($db);
header('Location: inventory.php');
What I'm having trouble with is that I have been unable to find a way to pass the 'item ID' and the value being modified to the update script. I can do it by passing the data of what I need through the value and then using list and explode to separate them but by doing that I'm displaying the item ID in each text field, which is not good.
If you know of a way to pass both pieces of data to the script, using the onchange function, I'd appreciate the assistance.
You can add it as a parameter to your onChange function, then update a hidden field on your form with this value before it is submitted.
PHP
updateInventory('update_inventory.php', ".$row['item_id'].")
JavaScript
function updateInventory(action, item_id){
// update hidden form value with item_id
document.getElementById('item_id').value = item_id;
document.getElementById('update_add_inventory').action = action;
document.getElementById('update_add_inventory').submit();
}
am developing an online application and i have a php search script that fetches required info from the database.I have managed to include a delete and update buttons to the script such that when a user searches for an item a table display of required data is displayed but then i dont know how to bind the buttons to their functionality. Am new with Php so any help is appreciated. Here is my search code...
<?php
// Get the search variable from URL
$var = #$_GET['s'] ;
$trimmed = trim($var); //trim whitespace from the stored variable
// rows to return
$limit=15;
// check for an empty string and display a message.
if ($trimmed == "")
{
echo "<p>Please enter a search value...</p>";
exit;
}
// check for a search parameter
if (!isset($var))
{
echo "<p>We dont seem to have a search parameter!</p>";
exit;
}
//connect to database
mysql_connect("localhost","root",""); //(host, username, password)
//specify database **
mysql_select_db("archive_sys") or die("Unable to select database"); //select which database we're using
// Build SQL Query
$query = "select * from tbl_archivingdetails where archiveid like \"%$trimmed%\" or buildingid like \"%$trimmed%\" or branchid like \"%$trimmed%\" or study like \"%$trimmed%\" or batchnumber like \"%$trimmed%\" or quantity like \"%$trimmed%\" or archivedate like \"%$trimmed%\" or archivedby like \"%$trimmed%\" or archiveeemail like \"%$trimmed%\" or archiveephone like \"%$trimmed%\" or expecteddestructiondate like \"%$trimmed%\" or currarchholderproj like \"%$trimmed%\" or currexpretdate like \"%$trimmed%\" or returnedby like \"%$trimmed%\" or status like \"%$trimmed%\"";
$numresults=mysql_query($query);
$numrows=mysql_num_rows($numresults);
// next determine if s has been passed to script, if not use 0
if (empty($s)) {
$s=0;
}
// get results
$query .= " limit $s,$limit";
$result = mysql_query($query) or die("Couldn't execute query");
// display what the person searched for
echo "<h2>You searched for: "" . $var . ""</h2>";
// begin to show results set
echo "Results: ";
$count = 1 + $s ;
//the begining of a table with a header
echo " <table border=2>";
echo "<tr align=center>";
echo "<th> Check Code </th>";
echo "<th> Archive ID </th>";
echo "<th> Building ID </th>";
echo "<th> Branch ID </th>";
echo "<th> Study </th>";
echo "<th> Batch Number </th>";
echo "<th> Quantity </th>";
echo "<th> Archive Date </th>";
echo "<th> Archived By </th>";
echo "<th> Archivee Email </th>";
echo "<th> Archivee Phone </th>";
echo "<th> Expected Destruction Date </th>";
echo "<th> currArchHolderProj </th>";
echo "<th> Current Exp Return Date </th>";
echo "<th> Returned By </th>";
echo "<th> Status </th>";
//echo "<th> Action </th><tr><td><input type='submit' name='Submit' value='Delete' /> | <input type='submit' name='Submit' value='Update' /> </td></tr>";
echo " </tr>";
// now you can display the results returned
while ($row= mysql_fetch_array($result)) {
$title = $row["archiveid"];
$title1 = $row["buildingid"];
$title2 = $row["branchid"];
$title3 = $row["study"];
$title4 = $row["batchnumber"];
$title5 = $row["quantity"];
$title6 = $row["archivedate"];
$title7 = $row["archivedby"];
$title8 = $row["archiveeemail"];
$title9 = $row["archiveephone"];
$title10= $row["expecteddestructiondate"];
$title11 = $row["currarchholderproj"];
$title12 = $row["currexpretdate"];
$title13 = $row["returnedby"];
$title14 = $row["status"];
echo" <tr>";
echo "<td><input type='checkbox' name='checkbox' value='".$row['archiveid']."' id='checkbox'/> </td> <td>".$title."</td> <td>".$title1."</td><td>".$title2."</td><td>".$title3."</td><td>".$title4."</td><td>".$title5."</td> <td>".$title6."</td><td>".$title7."</td><td>".$title8."</td><td>".$title9."</td><td>".$title10."</td> <td>".$title11."</td><td>".$title12."</td><td>".$title13."</td><td>".$title14."</td>" ;
echo " </tr>";
}
echo "<tr><tr> <td><input type='submit' name='Submit' value='Delete' /></td> | <td><input type='submit' name='Submit' value='Update' /> </td></tr>";
echo " </tr>";
echo " </table>";
//break before paging
echo "<br />";
?>
You could do this, change input buttons to links and append the archiveid to the link.
echo "<th> Action </th><tr><td><a href='delete.php?archiveid=" . title . '>Delete</a> | <a href='update.php?archiveid=" . title . '>Update</a> </td></tr>";
Now these links will send you to delete.php and update.php respectively
The examples below are sans security for brevity and will assume that you make connections to the db.
//delete.php
$archiveId = $_GET['archiveid'];
//now use your db connection to delete the record according to the archiveid
and in update.php
//update.php
$archiveId = $_GET['archiveid'];
/**
* Use your db connection to retrieve all the data that relates to this archiveid
* Populate a form with all the archive details so you can modify them
* Save the form details to the db when it has been submitted, validated and escaped
* The query should use an UPDATE statement
*/