How can I send url where I use sessions? - php

I use sessions in the products site. My problem is how can I send the single products datasheet site's url.
In the product datasheet site, I fill up the sessions when I click on a product's image in the index site:
<?php session_start(); include "connection.php";
$sql = mysql_query("SELECT * FROM products WHERE img = '".$_COOKIE['image_src']."'");
while ($f = mysql_fetch_array($sql))
{
$_SESSION['fid'] = $f['id']; //product id
$_SESSION['fimg'] = $f['image']; //product image
$_SESSION['fname'] = $f['name']; //product name
$_SESSION['fdecription'] = $f['decription']; //product description
$_SESSION['fcategory'] = $f['category']; //product category
}
?>
Than the same site I write out the sessions (the product infos):
e.g:
<?php session_start(); print ($_SESSION[fname]);
echo "<img src='".$_SESSION['fimg']."' height='350' width='250'>";?>
But this way always the last clicked products infos will be in the sessions.
And I can't open more than one product's datasheet at the same time.

You just need to create another "level" to your session array:
<?php
session_start();
include "connection.php";
$sql = mysql_query("SELECT * FROM products WHERE img = '".$_COOKIE['image_src']."'");
# Create a counter variable
$counter = 0;
while ($f = mysql_fetch_array($sql))
{
$_SESSION[$counter]['fid'] = $f['id']; //product id
$_SESSION[$counter]['fimg'] = $f['image']; //product image
$_SESSION[$counter]['fname'] = $f['name']; //product name
$_SESSION[$counter]['fdecription'] = $f['decription']; //product description
$_SESSION[$counter]['fcategory'] = $f['category']; //product category
# Increment the counter
$counter++;
}
?>
Then on the page which you want to view the images, just loop that array:
<?php
for( $i=0; $i<count($_SESSION); $i++ )
{
...
echo '<img src="'.$_SESSION[$i]["fimg"].'">';
...
}
?>
Multi-dimensional Arrays
PHP Docs - Arrays

I solve the problem:
Firstly I have to call the page this way: index.php?image_src=XY
Then I need to use $_GET insted of $_COOKIE.
Finally with this way the sessions are unnecessary.
<?php include "connection.php";
$sql = mysql_query("SELECT * FROM products WHERE img = '".$_GET['image_src']."'");
while ($f = mysql_fetch_array($sql))
{
$fid = $f['id']; //product id
$fimg = $f['image']; //product image
$fname = $f['name']; //product name
$fdecription = $f['decription']; //product description
$fcategory = $f['category']; //product category
}
?>
And I can write out the datas:
<?php echo "<img src='".$fimg."' height='350' width='250'>";
echo "$fdecription";
?>

Related

I don't get all the data from mysql - PHP

I've been searching for this for while but didn't find anything related.
So my problem is that I do get all the data from mysql with while(). However, all the articles I am trying to get displays as only 1 article even though the content is different. Sorry, it's not easy to explain that but see pictures below:
My database:
How it is displayed:
my articlesFunction.php code:
// check if user is logged in to view the content:
if(!isset($_SESSION['loggedin']) && !isset($_SESSION['loggedinAdmin'])){
header("Location: login.php");
}else{
}
//
$sql = "SELECT * FROM `articles` ORDER BY id DESC";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)){
$displayUsername = $row['username'];
$displayArticleName = $row['name'];
$displayArticleDescription = $row['description'];
$fullArticle = 'Article name: '.$displayArticleName.'<br/> This article was posted by: '.$displayUsername.'<br/>'.$displayArticleDescription.'<hr/>';
}?>
//
my articles.php:
<?php
///////////////////////////////////////////////////////////////////////////////////////
// UNFINISHED //
///////////////////////////////////////////////////////////////////////////////////////
session_start();
require_once 'connect.php';
include 'articlesFunction.php';
?>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Blog posts</title>
<link rel="stylesheet" href="css/articles.css">
</head>
<body>
<div id="bannerDiv" style="background-image: url(images/banner.jpg); background-size: 100% 100%; height:150px;">
<h2 id="bannerTitle"><u><i>Articles about travel that everyone loves...</i></u></h2>
<p>Homepage</p>
<span id="BannerMenu"><?php echo 'logged in as: '.$_SESSION['username'].' ';?></span><button>Logout</button>
</div>
<div id="container">
<div id="articles">
<div id="Display Articles">
<h1><u>Our set of articles:</u>
</h1>
<div id="display">
<?php
echo $fullArticle;
?>
</div>
</div>
</div>
</div>
</body>
</html>
So, I hope you understand my issue now. First, in this example, when I put it alone in the div, I only get the oldest article and I get only 1. If I add a while to the div, It gives me the results in the picture above:
So, how can I display the articles (all of them) and each one to be different as they are in the database.
You are overwriting your variable on every iteration of the while loop.
while($row = mysql_fetch_assoc($result)){
$displayUsername = $row['username'];
$displayArticleName = $row['name'];
$displayArticleDescription = $row['description'];
$fullArticle = 'Article name: '.$displayArticleName.'<br/> This article was posted by: '.$displayUsername.'<br/>'.$displayArticleDescription.'<hr/>';
}
so as a simple example
$a = 0;
$b = 3;
while($a < $b){
$output = $a;
$a++;
}
echo $output;
This gives back 2 because $output is being over written every-time. There are two approaches to keeping all the values.
Option one, concatenate the variable
$a = 0;
$b = 3;
$output = '';
while($a < $b){
$output .= $a;
$a++;
}
echo $output;
Which will output 012. We have to define the variable before using it with the .=. With the .= it is trying to concatenate the value first so it must already exist.
Option two, store the values in an array
$a = 0;
$b = 3;
while($a < $b){
$output[] = $a;
$a++;
}
print_r($output);
This will output:
Array
(
[0] => 0
[1] => 1
[2] => 2
)
This way is a bit more work because when you want to access it later you have to re-iterate through it. However it can be better if you want to be able to access each data point separately.
foreach($output as $value) {
echo $value;
}
Also note if users are providing their usernames, article name, or description and you aren't filtering that this will open you to XSS injections.
https://en.wikipedia.org/wiki/Cross-site_scripting
https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet#A_Positive_XSS_Prevention_Model
Usage in your actual code would be:
$sql = "SELECT * FROM `articles` ORDER BY id DESC";
$result = mysql_query($sql);
$fullArticle = '';
while($row = mysql_fetch_assoc($result)){
$displayUsername = $row['username'];
$displayArticleName = $row['name'];
$displayArticleDescription = $row['description'];
$fullArticle .= 'Article name: '.$displayArticleName.'<br/> This article was posted by: '.$displayUsername.'<br/>'.$displayArticleDescription.'<hr/>';
}?>
This should be your code, in order to avoid the errors you mentioned in the comments;
//init fullname variable
$fullArticle = '';
while($row = mysql_fetch_assoc($result)){
$displayUsername = $row['username'];
$displayArticleName = $row['name'];
$displayArticleDescription = $row['description'];
$fullArticle .= 'Article name: '.$displayArticleName.'<br/> This article was posted by: '.$displayUsername.'<br/>'.$displayArticleDescription.'<hr/>';
}?>
//

Dynamically create variables in foreach loop and use on another page

I'm using a dynamic template for a custom made CMS. I want to get variablesfrom one php-page and, for each created site that uses that page, I want to use the variables in a foreach to, for example display each title.
I have made a simple example below to explain this:
home.com/gallery/1
home.com/gallery/2
home.com/gallery/3
What I get:
Gallery 1
Gallery 1
Gallery 1
What I want:
Gallery 1
Gallery 2
Gallery 3
(Assuming that each page was named Gallery 1, 2, 3)
gallery.php
<form action="">
<input type="text" name="page_title">
</form>
<?php
$galleries = array();
$id = intval($_POST["id"]);
? foreach ($galleries as $id => $gallery) {
$title = $_POST["page_title"];
}
$_SESSION['galleries'] = $galleries;
$_SESSION['title'] = $title;
?>
<h1><?php echo $title; ?></h1>
page.php:
$galleries = $_SESSION['galleries'];
$title = $_SESSION['title'];
foreach ($galleries as $id => $gallery) {
echo $title;
echo "<br>";
}
?>
Note: because I want to use the variables on multiple pages I can't assign the form's action to a specific php-page.
Ok, I just found the sollution:
page.php:
$galleries = $_SESSION['galleries'];
$title = $_SESSION['title'];
foreach ($galleries as $id => $gallery) {
echo $gallery["title"]; //echo this line instead of $title
echo "<br>";
}
?>

Saving a value from a drop down to a variable PHP

I am trying to save the value selected in the date drop down box to a variable '$AvailabilityID' which is retrieved on the next page. The drop down box is populated from the MYSQL table bs_availability. From what I've read I need to use Javascript but really no idea how to do it.
Any help appreciated.
<?php
//current URL of the Page. cart_update.php redirects back to this URL
$current_url = base64_encode("http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
$results = $mysqli->query("SELECT SessionType, SessionName, SessionCost, SessionID FROM bs_session
GROUP BY SessionName ORDER BY SessionType ASC;");
if ($results) {
//output results from database
while($obj = $results->fetch_object())
{
$availabilityresults = $mysqli->query("SELECT * From bs_availability WHERE sessionID = ".$obj->SessionID.";");
echo '<tr>';
echo '<form method="post" action="cart_update.php">';
echo '<td>'.$obj->SessionName.'</td>';
echo '<td>'.$obj->SessionType.'</td>';
echo '<td><select name="date">';
//While loop to populate drop down with table data
while($objdate = $availabilityresults->fetch_object())
{
echo '<option value ="'.$objdate->AvailabilityID.'">'.$objdate->Date.'</option>';
}
echo '</select>';
echo '</td>';
echo '<td>Price '.$currency.$obj->SessionCost.' <button class="add_to_cart">Add To Cart</button></td>';
echo '</tr>';
echo '<input type="hidden" name="SessionID" value="'.$obj->SessionID.'" />';
echo '<input type="hidden" name="AvailabilityID" value="'.$objdate->AvailabilityID.'" />';
echo '<input type="hidden" name="type" value="add" />';
echo '<input type="hidden" name="return_url" value="'.$current_url.'" />';
echo '</form>';
echo '</div>';
}
}
?>
EDIT: This code is the cart_update.php. So when Add to Basket is pressed this script is run using the $SessionID from the selected item but I also need the AvailabiltyID of the chosen date so that I can run the right query to add the right date to the basket.
<?php
session_start(); //start session
include_once("config.php"); //include config file
//empty cart by distroying current session
if(isset($_GET["emptycart"]) && $_GET["emptycart"]==1)
{
$return_url = base64_decode($_GET["return_url"]); //return url
session_destroy();
header('Location:'.$return_url);
}
//add item in shopping cart
if(isset($_POST["type"]) && $_POST["type"]=='add')
{
$SessionID = filter_var($_POST["SessionID"], FILTER_SANITIZE_STRING); //product code
$AvailabilityID = filter_var($_POST["AvailabilityID"], FILTER_SANITIZE_STRING); //product code
$product_qty = filter_var($_POST["product_qty"], FILTER_SANITIZE_NUMBER_INT); //product code
$return_url = base64_decode($_POST["return_url"]); //return url
//limit quantity for single product
if($product_qty > 10){
die('<div align="center">This demo does not allowed more than 10 quantity!<br />Back To Products.</div>');
}
console.log($availabilityID);
//MySqli query - get details of item from db using product code
$results = $mysqli->query("SELECT SessionName, SessionCost FROM bs_session WHERE SessionID=$SessionID LIMIT 1");
//$results = $mysqli->query("SELECT bs_session.SessionName, bs_availability.Date, bs_session.SessionCost FROM bs_availability INNER JOIN bs_session ON bs_session.SessionID=bs_availability.SessionID WHERE bs_availability.AvailabilityID=$AvailabilityID LIMIT 1");
$obj = $results->fetch_object();
if ($results) { //we have the product info
//prepare array for the session variable
$new_product = array(array('name'=>$obj->SessionName, 'code'=>$SessionID, 'date'=>$obj->Date, 'price'=>$obj->SessionCost));
if(isset($_SESSION["products"])) //if we have the session
{
$found = false; //set found item to false
foreach ($_SESSION["products"] as $cart_itm) //loop through session array
{
if($cart_itm["code"] == $SessionID){ //the item exist in array
$product[] = array('name'=>$cart_itm["name"], 'code'=>$cart_itm["code"], 'date'=>$cart_itm["date"], 'price'=>$cart_itm["price"]);
$found = true;
}else{
//item doesn't exist in the list, just retrive old info and prepare array for session var
$product[] = array('name'=>$cart_itm["name"], 'code'=>$cart_itm["code"], 'date'=>$cart_itm["date"], 'price'=>$cart_itm["price"]);
}
}
if($found == false) //we didn't find item in array
{
//add new user item in array
$_SESSION["products"] = array_merge($product, $new_product);
}else{
//found user item in array list, and increased the quantity
$_SESSION["products"] = $product;
}
}else{
//create a new session var if does not exist
$_SESSION["products"] = $new_product;
}
}
//redirect back to original page
header('Location:'.$return_url);
}
//remove item from shopping cart
if(isset($_GET["removep"]) && isset($_GET["return_url"]) && isset($_SESSION["products"]))
{
$SessionID = $_GET["removep"]; //get the product code to remove
$return_url = base64_decode($_GET["return_url"]); //get return url
foreach ($_SESSION["products"] as $cart_itm) //loop through session array var
{
if($cart_itm["code"]!=$SessionID){ //item does,t exist in the list
$product[] = array('name'=>$cart_itm["name"], 'code'=>$cart_itm["code"], 'qty'=>$cart_itm["qty"], 'price'=>$cart_itm["price"]);
}
//create a new product list for cart
$_SESSION["products"] = $product;
}
//redirect back to original page
header('Location:'.$return_url);
}
In PHP, this is done through the POST array on your cart_update.php page:
if (isset($_POST['date'])){
$AvailabilityID = $_POST['date'];
}
You could also change the existing add to cart button to give it a name that will appear in the POST array:
echo '<td>Price '.$currency.$obj->SessionCost.' <button class="add_to_cart" name="add_to_cart">Add To Cart</button></td>';
This is often used as a check on the processing page, with an if block around all of the processing code.
if (isset($_POST['add_to_cart'])){
//all processing code here
}
Just use the POST Variable $_POST['date'] which holds the selected option value.

Concrete5 User attributes

I figured out how to du this seperatly
Display the user attribute:
<?php
//Create a User object (of the current User)
$u = new User();
//Creat a UserInfo object with the user ID
$ui = UserInfo::getByID($u->getUserID());
//Get the Value of your user Attribute
$value = $ui->getAttribute('name');
//Print it out
echo $value;
?>
Display page owner:
<?php
$ownerID = $cobj->getCollectionUserID();
$uia = UserInfo::getByID($ownerID);
$ownerName = $uia->getUserName();
echo $ownerName
?>
But i cannot figure out how to put them together so it displays the attribute('name'); of the page owner
Can you guys please help
Thanks
After moving a little bit more around with the codes.
i figured out that i just needed to move the
$cobj->getCollectionUserID();
into
$ui = UserInfo::getByID($u->getUserID());
So the finished code:
<?php
//Creat a UserInfo object with the Owner
$ui = UserInfo::getByID($cobj->getCollectionUserID() );
//Get the Value of your user Attribute
$value = $ui->getAttribute('name');
//Print it out
echo $value;
?>

Shopping cart output

I have an online store. A products page that allows the user to view a product and add it to the basket. It is added to the basket by clicking "Add to basket" button.
When a user clicks "add to basket", the script redirects them to the basket page and adds the product to the basket.
My question is, how do I print the basket output on the "basket.php" page? How do I pass the session content into variables to be printed?
Thank you.
"products" table in the database:
id int(11), name varchar(255), price int(11)
product.php
...
<form id="basket" name="basket" method="post" action="basket.php">
<input type="hidden" name="p_id" value="<?php echo $id; ?>"/>
<input type="submit" name="submit" value="Add to basket"/>
</form>
...
basket.php
<?php
//add product to cart with product ID passed from previous script
if (isset($_POST["p_id"]))
{
$p_id = $_POST["p_id"];
$q = mysql_query("SELECT * FROM products WHERE id='$p_id'");
$is = mysql_fetch_row($q); $is = $is[0];
$result = "";
while($row = mysql_fetch_array($q)) {
$name = $row["name"];
$price = $row["price"];
$info = $row["info"];
}
$result .= $name .= $price .= $info;
//$_SESSION['p_id'] contains product IDs
//$_SESSION['counts'] contains item quantities
// ($_SESSION['counts'][$i] corresponds to $_SESSION['p_id'][$i])
//$_SESSION['p_id'][$i] == 0 means $i-element is 'empty' (does not refer to any product)
if (!isset($_SESSION["p_id"]))
{
$_SESSION["p_id"] = array();
$_SESSION["counts"] = array();
}
//check for current product in visitor's shopping cart content
$i=0;
while ($i<count($_SESSION["p_id"]) && $_SESSION["p_id"][$i] != $_POST["p_id"]) $i++;
if ($i < count($_SESSION["p_id"])) //increase current product's item quantity
{
$_SESSION["counts"][$i]++;
}
else //no such product in the cart - add it
{
$_SESSION["p_id"][] = $_POST["p_id"];
$_SESSION["counts"][] = 1;
}
}
?>
<div>
<?php echo $result ?>
</div>
create ajax request on button click, to basket.php with GET veriable todo='add_to_basket', witch you will handle in basket.php
HTML of you add product button or link
Your count of product, you will get by Jquery, just type your count html selectors with IDs
<select id="count_<?=$YOUR_PRODUCT_ID?>"></select>
function add_to_basket(product_id){
var product = {};
product['prod_id'] = product_id;
//here you get count of current product
product['count'] = $("count_"+product_id).val();
$.ajax({
type: "GET",
url: "your_domain/basket.php?todo=add_to_basket",
data: "product",
success:function () {
}
});
}
on your basket.php you handle this request like that
if ($GET['todo'] == "add_to_basket"){
// here you add your data(witch comes from ajax) to SESSION
$_SESSION['basket'] [$GET['prod_id']] = $GET['count'];
return true;
}
then when user click on basket image you redirect him to basket page, in wich you display all product in session
<?foreach ($_SESSION['basket'] as $item){?>
// here you get product info by product id from your database and product count from $_SESSION print it to view , price wille be count*price
<?}?>

Categories