Passing session variables from html form to multiple php page urls? - php

I'm trying to pass variables from the form to multiple pages in php
The form "rentcheck.php"
<?php require ("Connections/Project.php") ;?>
<?php session_start();?>
<title>Rent Check</title>
</head>
<body>
<form id="form1" name="form1" method="post" action="rent.php">
<table width="385" height="70" border="1">
<tr>
<td><label for="select3">Select Customer</label>
<select name="Customer_ID" id="Customer_ID">
<?php
//Select from SQL Database Table (t_customer)
$sql=mysql_query("SELECT * from t_customer");
while ($Customer = mysql_fetch_array($sql)){
echo "<option value='".$Customer['Customer_ID']."'>".$Customer['Customer_Name']."</option>";
}
?>
</select></td>
</tr>
</table>
<p>
<input type="submit" name="button" id="button" value="Submit" />
</p>
</form>
</body>
</html>
After input and Pass it to page "rent.php"
<?php
require("Connections/Project.php");
//$_SESSION['yourvariable'] = 'foo';
//$newDate = date("d-m-Y", strtotime($row_Recordset1['Customer_CC_Exp_Date']));
session_start();
$datetoday=date("Y-m-d H:i:s");
$endOfCycle=date('Y-m-d', strtotime("+30 days"));
if(isset($_GET['page'])){
$pages=array("products","cart");
if(in_array($_GET['page'], $pages)){
$_page=$_GET['page'];
}else{
$_page="products";
}
}else{
$_page="products";
}
?>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Rent</title>
</head>
<body>
<p> <?php require($_page. ".php");?>
<?php echo $_POST['Customer_ID'];?></p>
</body>
</html>
This page (rent.php) shows the value from the form.
And the third page "products.php"
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<?php
if(isset($_GET['action']) && $_GET['action']=="add"){
$custget=$_SESSION['Customer_ID'];
$id=intval($_GET['id']);
if(isset($_SESSION['cart'][$id][$custget])){
$_SESSION['cart'][$id]['quantity']++;
$getcust=$_SESSION['Customer_ID'];
}else{
$sql_s="SELECT * FROM t_dvd_copy
WHERE dvd_copy_id={$id}";
$query_s=mysql_query($sql_s);
if(mysql_num_rows($query_s)!=0){
$row_s=mysql_fetch_array($query_s);
$_SESSION['cart'][$row_s['dvd_copy_id']]=array(
"quantity" =>1,
"price" => $row_s['price']
);
}else{
$message="NO";
}
}
}
?>
<?php if(isset($message)) {
echo"$message"; }
//echo print_r($_SESSION['cart']); ?>
<table width="489" height="52" border="1">
<tr>
<td width="123">DVD Copy ID</td>
<td width="120">Name</td>
<td width="91">Price</td>
<td width="127">Action</td>
</tr>
<?php
$sql="SELECT *, dvd_title FROM t_dvd_copy INNER JOIN t_dvd ORDER BY dvd_title ASC";
$query=mysql_query($sql);
while($row=mysql_fetch_array($query)) {
?>
<tr>
<td><?php echo $row['dvd_copy_id']?></td>
<td><?php echo $row['dvd_title']?></td>
<td><?php echo $row['price']?></td>
<td>Add To Cart</td>
<?php
}
?>
</table>
<body>
</body>
</html>
This page (products.php) shows:
Notice: Undefined index: Customer_ID in C:\xampp\htdocs\project3\rent.php on line 39" whenever I clicked the "Add to Cart" or manually type "rent.php?=cart".
I'm trying to do is to show(Customer_ID)/pass the variables on multiple pages("products.php","cart.php").
Any suggestions or ideas?

I think your problem is that you have not started the session on the other pages.
on every php page that you want to have a session you need to put session_start(); at the top.
if you don't the session will end and empty all the data from it.
if you want to make sure what is in your session you can print it out like so:
echo "<pre>";
echo print_r($_SESSION);
echo "</pre>";

Couple of things:
You mentioned that when you clicked "Add to Cart" it didn't work. I assume you mean the button labelled "Submit" on the rentcheck.php page. Can you confirm this is right please?
You would get an error when manually navigating to rent.php?=cart as you are looking for a Customer_ID key in the $_POST array but at this point you are not posting to the server, you are performing a $_GET request.
You have referenced $_SESSION['Customer_ID'] but I cannot see in your code where you have set this (products.php 7th line of code).
I would suggest thinking through how a user might navigate through your website:
where are they likely to start?
what variables will be available to you at this point?
what will you do if the required variables do not exist (e.g. $_SESSION)?
what is the earliest point you can collect the required information (your form)?
once the form has been completed correctly, how can I make sure that the required information is retained throughout the users session?
have I continued to test on each page that my required variables are available to me?
Start with that and see where it leads you.

Looking at the code I can see that you are including products.php inside rent.php
So a couple of thoughts here:
products.php should not have HTML <head> because it will be rendered
inside the <body>
If you have a variable available in rent.php it will be available
under the same name in products.php.
So if you have in rent.php:
$customer_id = $_POST['Customer_ID'];
require('products.php');
In products.php you can use $customer_id directly.

Related

How to store a multiple row query in a session var and use it with foreach

*I'm trying to carry my SQL query from PHP Controller file to my PHP View file. I've been cudgeling my brain for hours and hours. I've discovered that my major problem is that I don't know to carry data from PHP to another document that didn't start the REQUEST petition. The PHP Controller code (request) comes from a submit of other document (votar1.php).
I know to do it only if I pressed a button (type button) with onclick, but no idea when the code is triggered by submit button. Embbeding javascript on php doesn't works for me in any way.*
↓↓↓↓↓↓↓↓↓ (Focus on this better). ↓↓↓↓↓↓↓↓↓↓↓↓
Buuut, I think I'm close to the solution now, I've been experimenting with storing a query in a SESSION, so I would prefer this solution. It seems simple when the query returns you only one row, but when it returns more than one row, I don't know how to deal with it. So I need to know:
How to store multiple row query in a SESSION
How to use it (↑) to show data in a table using foreach.
I would be very thankful if you guide me a bit about these 2 things mentioned above ↑ (please, don't forget about the second one, because I don't know how to deal with that).
Controller(controladorPartidos.php):
include 'conexionBBDD.php';
session_start();
----other code----
if (passwordMatch($nif, $password) && (!haVotado($nif))) { //si la contraseña es correcta y no ha votado...
$consulta = "SELECT LOGO, NOMBRE FROM partido";
$resultado = $conexion->query($consulta);
while ($rows = mysqli_fetch_assoc($resultado)) {
$query=array_push($_SESSION['query'], $rows);
}
header('Location: Vista/votar2.php');
}
PHP View (votar2.php):
<?php
include_once 'header.html';
session_start();
$query = $_SESSION['query'];
?>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="javascript.js"></script>
<title></title>
</head>
<body>
<div id="caja">
<form action="../controladorPartidos.php" name="formVotar2" id="formVotar2" method="post">
<table>
<?php foreach ($query as $partido) { ?>
<tr>
<td style="text-align: center"><img src="<?php echo $partido[0] ?>"/></td>
<td><input type="radio" name="partido" value="<?php echo $partido[1] ?>"><?php echo $partido[1] ?></td>
<?php }; ?>
</tr>
</table>
<div style="width:75px; margin-right:auto; margin-left:auto;">
<br/>
<input id="botonVotar" type="submit" name="submit" onClick="submitVoto()" value="Votar"/>
<br/>
</div>
</form>
</div>
</body>
</html>
I hope you can help me! Thank you in advance for your time :)

display username based results, when logged in as another user (teacher tracking)

I have the following php page in which I am trying to simulate a simple example of searching for a specific username (stored in the database) and when "submit" is clicked, the results for that user are displayed on the page. At the moment, the code shows the results displayed only for the user that is logged in. How do I adapt it to fit with the code to search and track as another user?
HTML:
<p>Welcome, teachers! Here you can track student progress.</p>
<p>Enter the username of the student you wish to 'view' results for</p>
<form action="/action_page.php">
Username: <input type="text" name="FirstName" value="Mickey"><br>
<input type="submit" value="Submit">
</form>
Php related code that only allows the page to load if the user is logged in:
session_start();
if (!isset($_SESSION['username']) or ($_SESSION['username'] == '')) {
header("Location: login.php");
}
?>
Php code that displays the currently logged in user's quiz results:
<table class="table table-hover" style="text-align:center;">
<thead>
<tr>
<th style="text-align:center;">Quiz</th>
<th style="text-align:center;">Score (%)</th>
<th style="text-align:center;">Certificate</th>
<th style="text-align:center;">Retake</th>
</tr>
</thead>
<tbody>
<?php
$a = new NewQuizScore;
$scores = $a->getScores($_SESSION['username']);
foreach ($scores as $score) {
echo ("<tr>");
echo ("<td>".$score[0]. "</td> ");
echo ("<td>".$score[1]. "</td> ");
echo ('<td>Print Certificate</td>');
echo ("<td>Take it again!</td> ");
echo ("</tr>");
}
?>
</tbody>
</table>
</div>
</div>
To reiterate, as a php newbie, I would like a solution (with code in my existing context provided) for how to use the search button to look up a username, and then provide the information for the SEARCHED FOR username in the page, rather than for the username that is logged in. I've tried various things and cannot come up with the logic.
What I've tried:
Along the lines of:
<form action="/action_page.php">
Username: <input type="text" name="username1" value="username1"><br>
and:
$a = new NewQuizScore;
$scores = $a->getScores($_SESSION['username1']);
I was trying to link what is entered in the text box, to the getScores session, but obviously this doesn't work:
Update based on suggested answer - still doesn't work:
<?php
require 'includes/functions.php';
include_once 'config.php';
include 'includes/newquizscore.php';
session_start();
if (!isset($_SESSION['username']) or ($_SESSION['username'] == '')) {
header("Location: login.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form action="#" method="post">
Username: <input type="text" name="username1" value=""><br>
<input type="submit" value="Submit">
</form>
<?php
$username = (!empty($_POST['username1']))? $_POST['username1'] : $_SESSION['username'];
$a = new NewQuizScore;
# This is assuming this action is what you use to get the user's data
$scores = $a->getScores($username)
?>
</body>
</html>
You need to get the value from the form using the $_POST superglobal. $_POST is less transparent than $_GET, so I would use that for your form:
<!-- ADD METHOD ------------------------------->
<!------------------------------vvvvvvvvvvvvv-->
<form action="/action_page.php" method="post">
Username: <input type="text" name="username1" value=""><br>
<input type="submit" value="Submit">
</form>
When you post the form, you can use the script below. Note, since your form is pointing to /action_page.php, that is where this script should be located:
# Fetch the post value OR the current logged in (depending if form submitted or not)
# This is assuming you are searching by username1 value from form
# (since that is what you have in your form). You can use functions like
# trim() to remove empty spaces before and after submitted value to clean
# the input up a bit
$username = (!empty($_POST['username1']))? $_POST['username1'] : $_SESSION['username'];
$a = new NewQuizScore;
# This is assuming this action is what you use to get the user's data
$scores = $a->getScores($username);

Login issue with PHP Session

Hi I have meet a problem here.
I need to log in an account here
but after i key in all the details and click Sign-In the page will redirect me back to the log in page. But actually the account is already logged in just that it cant redirect back to the Home Page after log in.
What problem is this? Im using Session.
and i put my session_start in connect.php(which is use to connect to database)
Below is The Code
<?php error_reporting(0) ?>
<?php
include_once 'connect.php';
//Code Refer to http://www.w3schools.com/php/func_http_setcookie.asp
if(isset($_SESSION['user'])!="")
{
header("Location: Home.php");
}
if(isset($_POST['btn-login']))
{
$username = mysql_real_escape_string($_POST['username']);
$upass = mysql_real_escape_string($_POST['password']);
$res=mysql_query("SELECT * FROM user WHERE u_username='$username'");
$row=mysql_fetch_array($res);
if($row['u_password']==md5($upass))
{
$_SESSION['user'] = $row['u_ID'];
header("Location: Home.php");
}
else
{
?>
<script>alert('wrong details');</script>
<?php
}
?>
<?php
$year = time() + 31536000;
setcookie('rememberme', $_POST['username'], $year);
if ($_POST['rememberme'])
{
setcookie ('rememberme',$_POST['username'], $year);
}
else
{
setcookie(rememberme, $past);
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Login</title>
<link rel="stylesheet" href="Style.css" type="text/css" />
</head>
<body>
<div id="header">
<div id="left">
<label>AngelService</label><br/>
<p>Royal Borough of Greenwich</p>
</div>
</div>
<center> Home Page | View Post | Post A Service</center>
<center>
<div id="login-form">
<form method="post">
<table align="center" width="30%" border="0">
<tr>
<td><input type="text" name="username" placeholder="Your Username" required value="<?php
echo $_COOKIE['rememberme']; ?>"/>
</td>
</tr>
<tr>
<td><input type="password" name="password" placeholder="Your Password" required />
</td>
</tr>
<tr>
<td><button type="submit" name="btn-login">Sign In</button></td>
</tr>
<tr>
<td>
<input type="checkbox" name="rememberme" value="rememberme" style="font- size:6px;"> Remember Me<br>
</td>
</tr>
<tr>
<td>
Sign Up Here</td>
</tr>
</table>
</form>
</div>
</center>
<div id="footer">
<div id="center" align="center">
<br/>
<p>Angel Services | Royal Borough of Greenwich | Created By UOG Student: Kuai Boon Ting</p>
</div>
</div>
</body>
</html>
You are missing action="Your redirection page" in form tag i.e.,
<form method="post" action="forexample-Home.php">
.....
</form>
There are several things you can do to improve your code. For starters, you do not need to close and open PHP tags directly after each other, like you have
<?php error_reporting(0) ?>
<?php
include_once 'connect.php';
could just be
<?php error_reporting(0);
include_once 'connect.php';
The statement if(isset($_SESSION['user'])!="") doesn't do exactly what you think it does. isset($_SESSION['user']) returns a boolean (true/false), so checking whether or not a boolean is empty won't work. You can do if (!empty($_SESSION['user'])) {... to check if it's set and if it's empty or not. Check out the documentation for isset() and documentation for empty().
For your actual problem though: Note also that your header(); functions cannot be called after any output is made to the browser (any whitespace, HTML or PHP echo). This would appear as a PHP Warning, which will be reported should you put error_reporting(-1); instead of ignoring all errors (as you currently are doing with having error_reporting set to 0).
The other answer suggested using the HTML action-attribute for the form, but in case the login is invalid, it's best to have it sent to the same page, and only redirect should the login be valid. This is called "validate and redirect".
These pointers below are just to improve your code, and not necessarily the cause of your problem.
If you want to set a cookie, it has to be done before any and all output is sent to the browser (see this post), so in case the if($row['u_password']==md5($upass)) statement fails, and it enters the else-brackets, your cookie will not be set.
You should stop using mysql_* functions if you can. They are deprecated, and will be removed in the future. Switch over to mysqli_* or PDO instead. (Check out this post).
Usage of md5 hashing is not that secure. If you have PHP 5.5.0 or higher, you should perhaps look into usage of password_hash and password_verify
After every header("Location: ...."); you should always put a exit;, so that the code stops executing after it's redirecting. (Check out this post).

$_GET not working properly

i have a code in which i received two variable($isbn,$eno) from former page via form GET method but these two variables are not working if i am not echo out it on my page the code for the same is given below.
<?php
error_reporting(E_ALL);
require 'db/connect.php';
if(isset($_POST['generatereport']))
{
$isbn=$_GET['isbn'];
$eno=$_GET['eno'];
echo $eno; //if this is not done then i am not receiving data from database
echo $isbn; //if this is not done then i am not receiving data from database
$studentdata="select * from users where eno='$eno'";
if($studentresult=$db->query($studentdata))
{
$studentrow = $studentresult->fetch_assoc();
}
else
{
echo"fetching error";
}
$bookdata="select Lpad(isbn,'10','0') as isbn,book_name from book_data where isbn='$isbn'";
if($bookresult=$db->query($bookdata))
{
$bookrow = $bookresult->fetch_assoc();
}
else
{
echo"fetching error";
}
}
?>
<!doctype html>
<html lang='en'>
<head>
</head>
<body>
<div id='report'>
<table>
<tr><td><h3>Issue Report</h3></td></tr>
<tr><td><h4>Student details</h4></td></tr>
<tr><td>UNIQUE ID:<?php //random number here ?></td></tr>
<tr><td>Enrollment:<?php echo $eno; ?></td></tr>
<tr><td>Name:<?php echo strtoupper($studentrow['fname']);echo strtoupper( $studentrow['lname']); ?></td></tr>
<tr><td>Branch:<?php echo strtoupper($studentrow['branch']); ?></td></tr>
<tr><td>Semester:<?php echo $studentrow['sem']; ?></td></tr>
</table>
<hr/>
<table>
<tr><td><h4>Book details</h4></td></tr>
<tr><td>isbn:<?php echo $bookrow['isbn']; ?></td></tr>
<tr><td>Book Name:<?php echo strtoupper($bookrow['book_name']);?></td></tr>
</table>
<hr/>
<form action="script/issue.php?isbn=<?php echo $isbn;?>" method='post' id='report'>
<input id="btn_issue" type="button" value="Issue this Book"/>
<input id="btn_close" type="button" value="cancel"/>
</form>
</div>
</body>
</html>
You need to set attribute name to inputs in your form, after that you can access to value by GET or POST
Change form method:
<form action="script/issue.php?isbn=<?php echo $isbn;?>" method='get' id='report'>
<input name ='isbn' id="btn_issue" type="button" value="Issue this Book"/>
<input name ='eno' id="btn_close" type="button" value="cancel"/>
</form>
Or get your variables from post, like:
$isbn=$_POST['isbn'];
$eno=$_POST['eno'];
change your from method to get
<form action="script/issue.php?isbn=<?php echo $isbn;?>" method='get' id='report'>
or you can use $_REQUEST in php which can read either get or post
If you use method="POST", it meant you should use $_POST for your next process. Can use $_REQUEST also. But I think $_POST is more specifics for method POST. Please read the documentation of PHP about form method again.

php - isset button

i try to solve a problem but didnt succeed. I retrieve datas from google analytics and i have to send start and end date. I have two textbox and user select start and end date.However, but before user select start and end date. The problem occurs..
The place that i use isset is here,
This is my full html
<?php
define('ga_email','mertmetinbjk#gmail.com');
define('ga_password','************');
define('ga_profile_id','*******');
require 'gapi.class.php';
require 'connectDB.php';
$ga = new gapi(ga_email,ga_password);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>İçerik</title>
<script language="javascript" type="text/javascript" src="datetimepicker.js">
//Date Time Picker script- by TengYong Ng of http://www.rainforestnet.com
//Script featured on JavaScript Kit (http://www.javascriptkit.com)
//For this script, visit http://www.javascriptkit.com
</script>
</head>
<div></div>
<body>
<table align="center">
<tr>
<td><br />
<br />
<form action="#" method="post" name="formDates" id="form1" >
<table width="303" height="40" border="0" align="center">
<table width =""
<tr>
<td>Başlangıç Tarihi</td>
<td>
<label for="txtStartDate"></label>
<input type="text" name="txtStartDate" id="txt1" value="" /><a href="javascript:NewCal('txt1','ddmmyyyy')"><img src="images/cal.gif" width="16" height="16" border="0" alt="Başlangıç Tarihi Seçin">
</a>
</td>
</tr>
<tr>
<td>Bitiş Tarihi</td>
<td>
<label for="txtEndDate"></label>
<input type="text" name="txtEndDate" id="txt2" /><a href="javascript:NewCal('txt2','ddmmyyyy')"><img src="images/cal.gif" width="16" height="16" border="0" alt="Bitiş Tarihi Seçin">
</a>
</td>
</tr>
</form>
<tr>
<td><input type="submit" name="btnSubmit" value="Gönder"</td>
</tr>
</table>
<table width="1250" height="26" align="center">
<tr>
<td width="138"><strong>Kanal Adı</strong>
<td width="150"><b>Kategori Adı</b></td>
<td width="130"><p><strong>Event Adı</strong></td>
<td width="145"><strong>Toplam</strong>
</tr>
</table>
<?php
if(isset($_POST['submit'])){
$startDate = $_POST['txtStartDate'];
$endDate = $_POST['txtEndDate'];
}
$arrDates = explode("-",$startDate);
$startDate=$arrDates[2]."-".$arrDates[1]."-".$arrDates[0];
$arrDates = explode("-",$endDate);
$endDate = $arrDates[2]."-".$arrDates[1]."-".$arrDates[0];
echo $startDate;
echo $endDate;
$ga->requestReportData(ga_profile_id,array('eventCategory','eventAction'),array('totalEvents'),$sort_metric=null,$filter='eventAction==InitPlayer',$start_date='2012-02-02',$end_date='2012-02-16');
foreach($ga->getResults() as $result2);
{
echo $result2->geteventCategory();
echo $result2->geteventAction();
echo $result2->gettotalEvents();
}
$ga->requestAccountData();
$mysql = new mysql();
$mysql->connect();
$counter = 0;
foreach($ga->getResults() as $result)
{
echo $result . ' (' . $result->getProfileId() . ")<br />";
echo "<br />";
$counter++;
}
$result = mysql_query("select profile_id from profiles");
$num_rows = mysql_num_rows($result);
if($counter != $num_rows)
{
$mysql->query("delete from profiles");
foreach($ga->getResults() as $result)
{
$mysql->query("insert into profiles values(".$result->getProfileId().",'".$result."')");
}
}
?>
</td>
</tr>
</table>
</body>
</head>
</html>
what is wrong?
if a choose start and end date problems is solved , problems occurs before that i choose
It must be isset($_POST["btnSubmit"]) NOT submit
submit = type
btnSubmit = name of the button
I think it should be:
if(isset($_POST['submit']))
instead of:
if(!isset($_POST['submit']))
The exclamation mark in front of isset means not. Also I would check for the actual fields you want to use, not for $_POST['submit']:
if(isset($_POST['txtStartDate']) && isset($_POST['txtEndDate']))
{
// Do something with $_POST['txtStartDate'] and $_POST['txtEndDate']
}
The reason you were getting the error is that $_POST['submit'] does not exist. There is not input element with a name attribute called submit. Beware of the difference between type and name.
Undefined index txtStartDate, ...
It seems that your form may not be conforming to the same variable name specification with the one that you use in this php file. Make sure field names are matching within the form and here.
And also you should make these checks in your php file after submission success: if(!isset($_POST['submit']))
When your page is loading and $_POST['submit'] is not set, your $_POST['txtStartDate'] and $_POST['txtEndDate'] are not set so $arrDates is not set too. You need to check if these $_POST vars are set or not, to work with them.
You have to use isset() on every variable, not just one variable. $_POST['txtStartDate'] and $_POST['txtEndDate'] and other variables are simply not defined, this means that they were not sent with the POST request.
I guess it should be if(isset($_POST['submit'])) instead of if(!isset($_POST['submit'])) as ! in the start means a negation
if(!isset($_POST['submit']))
This means that if the submit button was NOT pressed. You should check if the $_POST['submit'] is set, as a result of the form submission, like so:
if(isset($_POST['submit']))

Categories