Sim1980
asked on
Pass session variable to PHP page
Hi all.
I'm working on a webpage that displays some Google Charts based on the date parameter selected by the end user. There are 3 files:
(1) Reports1.php: The end user selects the date parameter. They click the "Run" button and it directs them to ChartTest2.html
(2) ChartTest2.html displays the Google Charts. It calls the file GetChartData1.php to get the data to populate the charts.
(3) GetChartData1.php: Selects the data to display on the charts in ChartTest2.html
Below is the code I have so far, I am not able to display anything in the charts after the end user selects the date and clicks the Run button in Reports1.php. Is it that my "ReportDate" session is empty?
Reports1.php:
ChartTest2.html:
GetChartData1.php:
I'm working on a webpage that displays some Google Charts based on the date parameter selected by the end user. There are 3 files:
(1) Reports1.php: The end user selects the date parameter. They click the "Run" button and it directs them to ChartTest2.html
(2) ChartTest2.html displays the Google Charts. It calls the file GetChartData1.php to get the data to populate the charts.
(3) GetChartData1.php: Selects the data to display on the charts in ChartTest2.html
Below is the code I have so far, I am not able to display anything in the charts after the end user selects the date and clicks the Run button in Reports1.php. Is it that my "ReportDate" session is empty?
Reports1.php:
<?php
require("common.php");
$_SESSION['ReportDate'] = $_POST['workscheduledate'];
?>
<!DOCTYPE html>
<head>
<title>Web App</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="style.css" type="text/css" />
<link href="iphone-icon1.png" rel="apple-touch-icon">
<script type="text/javascript" src="js/calendarDateInput.js">
</script>
</head>
<body>
<div class="wrapper">
<div id="logo"></div>
<form class="form4" action="Reports1.php" method="post">
<div class="formtitle4">Run Report</div>
<div class="input nobottomborder">
<div class="inputtext">New Schedule:</div>
<div style="width:80%;margin-left:40%;">
<script>DateInput('workscheduledate', true, 'YYYY-MM-DD')</script>
</div>
</div>
<div class="buttons" align = center>
<input class="button1" type="submit" formaction="ChartTest2.html" value="Run" />
<input class="button1" type="submit" formaction="Menu.php" value="Menu" />
</div>
</form>
</body>
</html>
ChartTest2.html:
<html>
<head>
<!--Load the AJAX API-->
<meta content="text/html;charset=utf-8" http-equiv="Content-Type" />
<meta content="utf-8" http-equiv="encoding" />
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
google.load("visualization", "1.1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart1);
// Callback that creates and populates a data table,
// instantiates the chart, passes in the data and draws it.
function drawChart1() {
var jsonData1 = $.ajax({
url: "GetChartData1.php",
dataType:"json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server
var data = new google.visualization.DataTable(jsonData1);
// Set chart options
var options = {'title':'Super Slab Workload',
'width':1300,
'height':700};
var view = new google.visualization.DataView(data);
view.setColumns([0, 1,
{ calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation" },
2,{ calc: "stringify",
sourceColumn: 2,
type: "string",
role: "annotation" },3,{ calc: "stringify",
sourceColumn: 3,
type: "string",
role: "annotation" }
]);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div1'));
chart.draw(view, options);
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div1"></div>
</body>
</html>
GetChartData1.php:
<?php
require("common.php");
$query ='SELECT Concat(x.firstname ," " ,x.lastname) as Name, sum(x.Slab) as Slab, SUM(x.DriedIn) as DriedIn, Sum(x.Slab) + Sum(x.DriedIn) as Total from (SELECT firstname, lastname, count(1) as Slab, 0 as DriedIn FROM Users INNER JOIN FieldSuperDataEntry ON Users.userid = FieldSuperDataEntry.UserID Where Type = 1 AND CreateDate > ":reportdate" group by firstname, lastname union all SELECT firstname, lastname, 0 as Slab, count(1) as DriedIn FROM Users INNER JOIN FieldSuperDataEntry ON Users.userid = FieldSuperDataEntry.UserID Where Type = 2 AND CreateDate > ":reportdate" group by firstname, lastname) x Group by Concat(x.firstname ," " ,x.lastname) order by Concat(x.firstname ," " ,x.lastname) ';
$query_params = array(
':reportdate' => $_SESSION['ReportDate']
);
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
$data = $stmt->fetchAll();
$rows = array();
$table = array();
$table['cols'] = array(
array('label' => 'Name', 'type' => 'string'),
array('label' => 'Dried In', 'type' => 'number'),
array('label' => 'Slab', 'type' => 'number'),
array('label' => 'Total', 'type' => 'number')
);
foreach($data as $row) {
$temp = array();
$temp[] = array('v' => (string) $row['Name']);
$temp[] = array('v' => (int) $row['DriedIn']);
$temp[] = array('v' => (int) $row['Slab']);
$temp[] = array('v' => (int) $row['Total']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
echo $jsonTable;
?>
Is the first line of common.php "session_start();"? if yes, then the problem is with Ajax,but if you don't have that line in common.php, put it at the very top and retry.
ASKER
Yes, "session_start();" is in the common.php file.
In GetChartData1, try adding the session variable to table array and then examine it in your ajax call. At least that way, you'll know whether it's being read correctly. If not, then maybe post your common.php file for us to take a look at
This PHP instruction is almost always your best friend:
http://php.net/manual/en/function.var-dump.php
http://php.net/manual/en/function.var-dump.php
On a side note, you should always have the following line in any PHP script that gets called by AJAX (e.g. GetChartData1.php)
On another side note, remember that once you set a session variable, it remains until the session is ended or you use the unset() function.
On a third side note, line 3 of Reports1.php will generate warnings in your log files every time a user loads the page for the first time. I usually use something like
That said, are you using Firefox with the Firebug plugin by any chance? It is immensely helpful in with debugging AJAX calls because it shows you what data is being sent and returned.
Have you looked in your server logs to see if there are any errors or warnings?
header("Cache-Control: no-cache, must-revalidate");
This avoids cached data being used (which might be causing your problem).On another side note, remember that once you set a session variable, it remains until the session is ended or you use the unset() function.
On a third side note, line 3 of Reports1.php will generate warnings in your log files every time a user loads the page for the first time. I usually use something like
if (isset($_POST['workscheduledate'])) { ... }
That said, are you using Firefox with the Firebug plugin by any chance? It is immensely helpful in with debugging AJAX calls because it shows you what data is being sent and returned.
Have you looked in your server logs to see if there are any errors or warnings?
@zappafan2k2: Great suggestion about Firebug!
ASKER
Thanks.
Ok, I'm trying to see where the issue may be so I commented out the session variable and instead changed the code to do a simple query based on the date parameter entered. Doing that it does not return any records, what am I doing wrong with the date parameters? I put # # on each end of the parameter but that didn't work. If I hard code the parameter to let's say '2013-10-28' then it displays data.
Ok, I'm trying to see where the issue may be so I commented out the session variable and instead changed the code to do a simple query based on the date parameter entered. Doing that it does not return any records, what am I doing wrong with the date parameters? I put # # on each end of the parameter but that didn't work. If I hard code the parameter to let's say '2013-10-28' then it displays data.
$query_params = array(
':reportdate' => $_POST['workscheduledate']
);
$query ="SELECT Concat(x.firstname ,'' ,x.lastname) as Name, sum(x.Slab) as Slab, SUM(x.DriedIn) as DriedIn, Sum(x.Slab) + Sum(x.DriedIn) as Total from (SELECT firstname, lastname, count(1) as Slab, 0 as DriedIn FROM Users INNER JOIN FieldSuperDataEntry ON Users.userid = FieldSuperDataEntry.UserID Where Type = 1 AND CreateDate > '#:reportdate#' group by firstname, lastname union all SELECT firstname, lastname, 0 as Slab, count(1) as DriedIn FROM Users INNER JOIN FieldSuperDataEntry ON Users.userid = FieldSuperDataEntry.UserID Where Type = 2 AND CreateDate > '#:reportdate#' group by firstname, lastname) x Group by Concat(x.firstname ,'' ,x.lastname) order by Concat(x.firstname ,'' ,x.lastname) ";
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
$data = $stmt->fetchAll();
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Ok I tried the following, but no data is displayed.
require("common.php");
header("Cache-Control: no-cache, must-revalidate");
$date = new DateTime($_POST['workscheduledate']);
$query_params = array(
':reportdate' => $date->format('Y-m-d')
);
var_dump($query_params);
$query ="SELECT Concat(x.firstname ,'' ,x.lastname) as Name, sum(x.Slab) as Slab, SUM(x.DriedIn) as DriedIn, Sum(x.Slab) + Sum(x.DriedIn) as Total from (SELECT firstname, lastname, count(1) as Slab, 0 as DriedIn FROM Users INNER JOIN FieldSuperDataEntry ON Users.userid = FieldSuperDataEntry.UserID Where Type = 1 AND CreateDate > ':reportdate' group by firstname, lastname union all SELECT firstname, lastname, 0 as Slab, count(1) as DriedIn FROM Users INNER JOIN FieldSuperDataEntry ON Users.userid = FieldSuperDataEntry.UserID Where Type = 2 AND CreateDate > ':reportdate' group by firstname, lastname) x Group by Concat(x.firstname ,'' ,x.lastname) order by Concat(x.firstname ,'' ,x.lastname) ";
try {
$stmt = $db->prepare($query);
$stmt->execute($query_params);
$data = $stmt->fetchAll();
} catch (Exception $e) {
var_dump($e->errorInfo);
}
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
When I do the following code, it displays the results. But when I remove the hardcoded date and put the parameter, that's when it displays nothing.
I then did the var_dump($query); as Ray suggested and in the WHERE statement it shows ":reportdate" instead of the actual date. The parameter is not being placed in the query.
$query ='SELECT Concat(x.firstname ," " ,x.lastname) as Name, sum(x.Slab) as Slab, SUM(x.DriedIn) as DriedIn, Sum(x.Slab) + Sum(x.DriedIn) as Total from (SELECT firstname, lastname, count(1) as Slab, 0 as DriedIn FROM Users INNER JOIN FieldSuperDataEntry ON Users.userid = FieldSuperDataEntry.UserID Where Type = 1 AND CreateDate > "2013-10-01" group by firstname, lastname union all SELECT firstname, lastname, 0 as Slab, count(1) as DriedIn FROM Users INNER JOIN FieldSuperDataEntry ON Users.userid = FieldSuperDataEntry.UserID Where Type = 2 AND CreateDate > "2013-10-01" group by firstname, lastname) x Group by Concat(x.firstname ," " ,x.lastname) order by Concat(x.firstname ," " ,x.lastname) ';
$stmt = $db->prepare($query);
$result = $stmt->execute();
$data = $stmt->fetchAll();
I then did the var_dump($query); as Ray suggested and in the WHERE statement it shows ":reportdate" instead of the actual date. The parameter is not being placed in the query.
Try omitting the quote marks around the :reportdate
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Article edited to emphasize the importance of omitting the quotes.
https://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/PHP_Databases/A_11177-PHP-MySQL-Deprecated-as-of-PHP-5-5-0.html
The colon-prefixed strings are placeholders, not quoted variable names. The are sent to PDO::Prepare() where they are used to match keys in the inputs that are passed to PDOStatement::BindParam() and / or PDOStatement:: Execute()
https://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/PHP_Databases/A_11177-PHP-MySQL-Deprecated-as-of-PHP-5-5-0.html
The colon-prefixed strings are placeholders, not quoted variable names. The are sent to PDO::Prepare() where they are used to match keys in the inputs that are passed to PDOStatement::BindParam() and / or PDOStatement:: Execute()
ASKER
Thanks zappa. I tried your code and got the following error:
array(1) { [0]=> string(5) "HY093" }
Warning: Invalid argument supplied for foreach() in /home/content/12/11231812/ html/GetCh artData1.p hp on line 104
It points to:
Which is where I hold the output of the page.
array(1) { [0]=> string(5) "HY093" }
Warning: Invalid argument supplied for foreach() in /home/content/12/11231812/
It points to:
foreach($data as $row) {
$temp = array();
$temp[] = array('v' => (string) $row['Name']);
$temp[] = array('v' => (int) $row['DriedIn']);
$temp[] = array('v' => (int) $row['Slab']);
$temp[] = array('v' => (int) $row['Total']);
$rows[] = array('c' => $temp);
}
Which is where I hold the output of the page.
ASKER
Ok. I tried the code below but I get the following error:
Parse error: syntax error, unexpected ':', expecting ')' in /home/content/12/11231812/ html/GetCh artData1.p hp on line 39
Line 39 is:
Parse error: syntax error, unexpected ':', expecting ')' in /home/content/12/11231812/
Line 39 is:
:reportdate => $date->format('Y-m-d')
require("common.php");
header("Cache-Control: no-cache, must-revalidate");
$date = new DateTime($_POST['workscheduledate']);
$query ='SELECT Concat(x.firstname ," " ,x.lastname) as Name, sum(x.Slab) as Slab, SUM(x.DriedIn) as DriedIn, Sum(x.Slab) + Sum(x.DriedIn) as Total from (SELECT firstname, lastname, count(1) as Slab, 0 as DriedIn FROM Users INNER JOIN FieldSuperDataEntry ON Users.userid = FieldSuperDataEntry.UserID Where Type = 1 AND CreateDate > :reportdate group by firstname, lastname union all SELECT firstname, lastname, 0 as Slab, count(1) as DriedIn FROM Users INNER JOIN FieldSuperDataEntry ON Users.userid = FieldSuperDataEntry.UserID Where Type = 2 AND CreateDate > :reportdate group by firstname, lastname) x Group by Concat(x.firstname ," " ,x.lastname) order by Concat(x.firstname ," " ,x.lastname) ';
$query_params = array(
:reportdate => $date->format('Y-m-d')
);
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
$data = $stmt->fetchAll();
ASKER
I got it to work. It turns out I cannot use the same parameter twice in the same query. So I did:
And that made the difference, I now see the data in the output.
$query_params = array(
':reportdate1' => $_POST['workscheduledate'],
':reportdate2' => $_POST['workscheduledate']
$query ='SELECT Concat(x.firstname ," " ,x.lastname) as Name, sum(x.Slab) as Slab, SUM(x.DriedIn) as DriedIn, Sum(x.Slab) + Sum(x.DriedIn) as Total from (SELECT firstname, lastname, count(1) as Slab, 0 as DriedIn FROM Users INNER JOIN FieldSuperDataEntry ON Users.userid = FieldSuperDataEntry.UserID Where Type = 1 AND CreateDate > :reportdate1 group by firstname, lastname union all SELECT firstname, lastname, 0 as Slab, count(1) as DriedIn FROM Users INNER JOIN FieldSuperDataEntry ON Users.userid = FieldSuperDataEntry.UserID Where Type = 2 AND CreateDate > :reportdate2 group by firstname, lastname) x Group by Concat(x.firstname ," " ,x.lastname) order by Concat(x.firstname ," " ,x.lastname) ';
);
And that made the difference, I now see the data in the output.
Couple of things of note. The reason you get the parse error in this line:
:reportdate => $date->format('Y-m-d')
is because you haven't put the reportdate in quotes. You build the parameter array like this:
:reportdate => $date->format('Y-m-d')
is because you haven't put the reportdate in quotes. You build the parameter array like this:
$query_params = array(
'reportdate1' => $date->format('Y-m-d'),
'reportdate2' => $date->format('Y-m-d')
);
When you var_dump($query) it will show the place holder (:reportdate). The named parameters don't get replaced - they get sent to the server separately.
ASKER
I'll close this question since I derailed it from the original question. I'll post another question for the session portion since at least I know the query works when passing parameters.
Thank you all for your help!
Thank you all for your help!