PHP + MySQL + Cookies, why is this not loading properly? - php

I've got a PHP page with 2 MySQL statements in various parts of the code. I'm using the generated result sets to set cookie values then call it later. Yet, when I call the cookie data, it does not update the display of the cookie values until after a 2nd refresh. To Better understand, Here's the 3 sections of code:
<?php
include 'functions.php';
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$SqlStatement = "SELECT Deceased.PK_Deceased, Deceased.Date_Death, Personal_Info.First_Name, Personal_Info.Last_Name FROM Deceased INNER JOIN Personal_Info ON Personal_Info.PK_Personal_Info = Deceased.FK_Personal_Info WHERE Deceased.FK_Personal_Info = '".$_POST['cboDeceased']."'";
$result = ExecuteSql($SqlStatement);
if(mysqli_num_rows($result) == 1)
{
$row = mysqli_fetch_array($result);
setcookie('deceasedID', $row['PK_Deceased'], time()+360000, '/');
setcookie('deceasedName', ($row['First_Name']." ".$row['Last_Name']), time()+360000, '/');
setcookie('deceasedDoD', $row['Date_Death'], time()+360000, '/');
}
}
?>
This is the code that pulls the data from the postback. I think that this is the part that is incorrect, but I'm not sure.
<tr>
<td width="25%" rowspan="2" align="center">Current User: <?php echo $_COOKIE['username']; ?> </td>
<td width="25%" rowspan="2" align="center">Current Deceased: <?php if(isset($_COOKIE['deceasedName']))echo $_COOKIE['deceasedName']; ?></td>
<td width="50%" rowspan="2" align="center">Deceased Date of Death: <?php if(isset($_COOKIE['deceasedDoD']))echo $_COOKIE['deceasedDoD']; ?></td>
This is the code to load the cookie data into fields and the part that takes the 2nd refresh to display properly.
<form action="<?php $_SERVER['PHP_SELF'];?>" method="post">
<table align="center" width="500" border="0.5">
<tr>
<td width="176" align="right" style="font-weight:bold;">Please select deceased:</td>
<td width="214">
<select name="cboDeceased" id="cboDeceased">
<option>Select...</option>
<?php
$SqlStatement = "SELECT Deceased.PK_Deceased , Personal_Info.First_Name, Personal_Info.Last_Name FROM Deceased INNER JOIN Personal_Info ON Personal_Info.PK_Personal_Info = Deceased.FK_Personal_Info";
$res = ExecuteSQL($SqlStatement);
while($row = mysqli_fetch_array($res))
{
echo "<option value='".$row['PK_Deceased']."'>".$row['First_Name']." ".$row['Last_Name']."</option>";
}
?>
This is the code that passes a variable based on ID to the 1st code block. This part works fine.
function ExecuteSQL($SQL)
{
$con = mysqli_connect("localhost", "root", "", "exec_support_db");
$res = mysqli_query($con, $SQL);
mysqli_close($con);
return $res;
}
Here's the code for the ExecuteSQL function. I know that this isn't the problem.
I think the problem is up above in the 1st code block, but I'm not sure. I've tried everything I can and am now out of ideas. Any help would be appreciated.

Beyond the SQL injection mentioned above by DaveRandom take a look at the php manual on how setcookie works:
http://php.net/manual/en/function.setcookie.php
It mentions specifically the info is injected into the headers, and therefor not available until your next page load. You probably want to do something like
if(isset($_COOKIE['deceasedID']))
{
$deceasedID = $_COOKIE['deceasedID'];
}
else
{
setcookie('deceasedID', $row['PK_Deceased'], time()+360000, '/');
$deceasedId = $row['PK_Deceased'];
}

Related

How to pass query results from the results page to a different php page

I know how to get search results from one page to another, but the scenario I'm in right now is that I have a search form (searchform.php) where the user enters search criteria into a field or fields, clicks the submit button and the results display in a table on the search.php page. Now what I need to do is send those query results to another page (list.php) which is a page formatted as a report. I've tried using $_SESSION, $_GET, foreach, etc. And I've also tried comparing my code with the code on the other pages on my site and on the internet, but to no avail. None seems to fit my situation. Right now I'm using $_SESSION and only getting the word "Array" in each column of the table and getting only one row of data. When I did get actual data from the query it only brought over the last result from the query. For example, the search.php showed 6 results, but the list.php page only showed the last result. I've spent days on this. Will someone please try to help me?
Here is part of the code on my search.php page (it works - although I'm not sure I need the $_SESSION info in the middle):
if !empty($_POST['id'])||!empty($_POST['title'])||!empty($_POST['numavail'])||!empty($_POST['categoryname'])||!empty($_POST['genretype'])){
$id = mysqli_real_escape_string($dbc, $_POST['id']);
$title = mysqli_real_escape_string($dbc, $_POST['title']);
$numavail = mysqli_real_escape_string($dbc, $_POST['numavail']);
$categoryname = mysqli_real_escape_string($dbc, $_POST['categoryname']);
$genretype = mysqli_real_escape_string($dbc, $_POST['genretype']);
$query="SELECT * FROM dvd WHERE (title LIKE '%$title%')
AND (numavail LIKE '%$numavail%')
AND (categoryname LIKE '%$categoryname%')
AND (genretype LIKE '%$genretype%')
ORDER BY title ASC";
}else {
$query="SELECT * FROM dvd ORDER BY title ASC";
}
$result = #mysqli_query ($dbc, $query);
$num = mysqli_num_rows($result);
if ($num > 0) { // If it ran OK, display all the records.
echo "<h4>Your search returned $num records.</h4><p></p>";
//Table header:
echo '<table align="center" width="950px" cellspacing="0" border=".5px" ! important><tr>
<th>Title</th><th>Qty</th><th>Category</th><th>Genre</th></tr>';
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
//Fetch all the records...
session_start();
$_SESSION['id']=['id'];
$_SESSION['title']=['title'];
$_SESSION['numavail']=['numavail'];
$_SESSION['categoryname']=['categoryname'];
$_SESSION['genretype']=['genretype'];
echo '<td align="left" width="20%" height="25px">'.$row['title'].'</td>
<td align="right" width="5%">'.$row['numavail'].'</td>
<td align="left" width="20%">'.$row['categoryname'].'</a></td>
<td align="left" width="30%">'.$row['genretype'].'</a></td>
<td align="center" width="5%"><a href=../dvd/updateform.php?id='.$row['id'].'><em>Update</em></a></td>
<td align="center" width="5%"><a href=../dvd/deleteconfirm.php?id='.$row['id'].'><em>Delete</em></a></td>
</tr>
';
}
// End of While statement
echo "</table>";
Here is part of the code on my list.php page (not working):
session_start();
include ('../../includes/reportheader.php'); // Include the header file.
echo ('<h1>DVD SEARCH RESULTS</h1>');
//Table displaying records.
'<div id="rpttable">';
echo '<table align="center" width="750px" cellspacing="0" border=".5px" ! important><tr>
<th>Movie Title</th><th>Qty</th><th>Category</th><th>Genre</th></tr>';
echo '<td align="left" width="20%" height="25px">'.$_SESSION['title'].'</td>
<td align="center" width="5%">'.$_SESSION['numavail'].'</td>
<td align="left" width="20%">'.$_SESSION['categoryname'].'</td>
<td align="left" width="30%">'.$_SESSION['genretype'].'</a></td>
</tr>
</div>
';
echo "</table>";
Move session_start(); at the first line of your document or else session will fail unless output buffering setting is on.
In your while loop, name your session variable properly so it won't mess with other session variables in the future. Also set the values of your session elements with that from $row variable.
From: $_SESSION['id']=['id']; - to - $_SESSION['search_result']['id'][]=$row['id']; - so on.
Also before your while loop you have to delete your previous search results before adding new ones by adding line unset($_SESSION['search_result']);. Else old and new results will be displayed together.
In listing.php you have to loop through $_SESSION['search_result'] to display the passed search results. Something like:
for($i=0; $i<count($_SESSION['search_result']['id']); $i++ ){
echo '<tr><td align="left" width="20%" height="25px">'.$_SESSION['search_result']['title'][$i].'</td>
<td align="center" width="5%">'.$_SESSION['search_result']['numavail'][$i].'</td>
<td align="left" width="20%">'.$_SESSION['search_result']['categoryname'][$i].'</td>
<td align="left" width="30%">'.$_SESSION['search_result']['genretype'][$i].'</a></td>
</tr>';
}
You can use GET, POST method or Session, Cookie for passing data from one page to another page
Example
GET and POST
<form method="get" action="page2.php">
<input type="hidden" name="varname" value="var_value">
<input type="submit">
</form>
PHP code
//Using GET
$var_value = $_GET['varname'];
//Using POST
$var_value = $_POST['varname'];
//Using GET, POST or COOKIE.
$var_value = $_REQUEST['varname'];
Change the method for the form to post if you want to do it via post.
Both are equally insecure, although GET is easier to hack.
GET method can handle less amount of data.
For handling higher amount of data, use POST Methode and also check the "post_max_size" in php.ini file.
Session
//One page 1
$_COOKIE['varname'] = $var_value;
//On page 2
$var_value = $_COOKIE['varname'];
Cookie
//One page 1
$_COOKIE['varname'] = $var_value;
//On page 2
$var_value = $_COOKIE['varname'];
The big difference between sessions and cookies is that the sessions value stored on the server and cookies stored in client browser memory.

Display data from database without using form tags?

I have a search form where the user will insert his/her CODE and NAME & TELEPHONE of that CODE will then be shown inside a table which is working fine (Thanks to stack overflow).
<form action="list25.php" method="post">
Search By code:<input type="text" name="code"><br><br>
<table border="0" width="100%" cellpadding="0" cellspacing="0" id="product-table">
<tr>
<th class="table-header-repeat line-left">Name</th>
<th class="table-header-repeat line-left">telephone</th>
</tr>
<?php
if (isset($_POST['search'])) {
$code = $_POST['code'];
$connect = mysqli_connect("localhost", "root", "", "sahmiye");
$query = "select * from balance where code = $code ";
$result = mysqli_query($connect, $query);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
?>
<tr>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['telephone']; ?></td>
</tr>
<?php
}
} else {
echo "Undifined ID";
$name = "";
$telephone = "";
}
mysqli_free_result($result);
mysqli_close($connect);
} else {
$name = "";
$telephone = "";
}
?>
</table>
<br><br>
<input type="submit" name="search" value="Find">
</form>
BUT i have a second completely different form as well and when the user writes his/her CODE in this second form i needed the NAME & TELEPHONE of that CODE to then be shown inside textboxes and the user will then fill up the rest of the form and then submit it so it can be saved into the database.
The problem being i know i cant have a form within a form but is there a way for me to run my first search form shown above with out using a form so that i can have the same function inside my second form whereby after CODE is given , it will fill up the textboxes with the NAME & TELEPHONE of that CODE ?
Display data from database without using form tags?
You need to use a GET array and use the parameter in the href.
I.e. and checking if it is set and not empty and equal to "something":
Name
Then use the GET array with the parameter.
if(!empty($_GET['var']) && $_GET['var'] == 'John'){
// do your thing to search for the string "John", as an example.
// ATT'N: John and john in the database are two different animals.
}
Use the same format for the other href.
Sidenote: Remove the href's from inside the <form></form> tags, as it may cause some havoc.
You will also need to quote the variable in the query when it is a string.
I.e.:
$query = "select * from balance where code = '$code' ";
...if $code is a string.
However, it will throw an error if the query contains characters that MySQL will complain about such as John's Bar & Grill, therefore a prepared statement/escaping the value will be required and will help prevent a possible SQL injection at the same time.
Reference:
https://en.wikipedia.org/wiki/Prepared_statement
Edit:
Going over the question again and TBH is a bit complicated, using sessions would be something to use in order to keep the values.
http://php.net/manual/en/session.examples.basic.php
...then checking if any of the session array(s) is/are set and not empty.
N.B.: session_start(); must reside inside all pages using sessions in order for this to work. Inputs can also contain sessions-related code and "if set/not empty". Otherwise, you will get errors about them being undefined.

How to print out a table from mySQL database inside a html/php page

i am trying to print out this table from phpmyadmin to my html/php page as a normal table. this is my coding for the page
Any help would be appreciated
Thanks
Looks like You were Using PDO , and all of a sudden you jump into old data fetching technique using mysql_*
My advice is to stick with PDO structure . SO you have to some little things
on line 6 use
$stmt->rowCount();
to get user row
then use
$data = $stmt->fetchAll();
to get database rows , You'll get an object .
Now You just need to loop through object for example
foreach ( $data as $rows ){
echo $rows->users;
}
Try this code:
<?php
$db = new mysqli("localhost", "root", "", "hangman");
?>
<table border="1">
<tr>
<td>User</td>
<td>Score</td>
</tr>
<tr>
<?php
$sql = "SELECT * FROM usernames";
$result = $db-query($sql);
while($row = mysqli_fetch_assoc($result)) {
?>
<td><?php echo $row['users']; ?></td>
<td><?php echo $row['Scores']; ?></td>
<?php
}
?>
</tr>
</table>
give me a comment if any errors.

Display mysql database query result on second pages

I have a mysql database with some data.here i display data on one page Now I want to display this data on next page please give me suggestion how I can do this .........
I need some modifications in this code like
I want to display table this table on next page(book.php page that is populated with the database)......
Second thing that I need to know is it possible to store the value of calendar in session variable (is it ???than how?)
<?php
if(isset($_POST['search'])){
$from = $_POST['from'];
$to = $_POST['to'];
$query = mysql_query("select * from schedule where Destinatio='$from' AND Arriva ='$to'");
$c = mysql_num_rows($query);
if (!$query) {
die('Invalid query: ' . mysql_error());
}
if($c>0)
{
?>
<table>
<tr align="center"><td width="120"><span class="style23">Destination</span> </td>
<td width="57"><span class="style23">Arrival</span></td>
<td width="121"><span class="style23">Departure time</span></td>
<td width="98"><span class="style23">Arrival Time</span></td>
<td width="44"><span class="style23">Fare</span></td>
<td width="85"><span class="style23">Bus_type</span></td>
<td width="84"><span class="style23">Total_Seats</span></td>
<td width="81"><span class="style23">Available</span></td>
<td width="52"> </td>
</tr>
</section>
<?php
while($r1 = mysql_fetch_array($query))
{
$schedule= $r1['id'];
$Destinatio = $r1['Destinatio'];
$Arriva= $r1['Arriva'];
$Departure_time = $r1['Departure_time'];
$Arrival_time = $r1['Arrival_time'];
$Fare = $r1['Fare'];
$Bus_type = $r1['Bus_type'];
$Total_Seats = $r1['Total_Seats'];
$bust = $schedule.'schedule';
$query1 = mysql_query("SELECT * from $bust where status='Available'");
echo $query1;
if (!$query1) {
die('Invalid query: ' . mysql_error());
}
$c = mysql_num_rows($query1);
?>
<tr align="center"><td><?php echo $Destinatio;?></td><td><?php echo $Arriva;?></td><td><?php echo $Departure_time;?></td><td><?php echo $Arrival_time;?></td><td><?php echo $Fare;?></td><td nowrap="nowrap"><?php echo $Bus_type;?></td><td><?php echo $c;?></td><td>Book
</td>
</tr></table>
</form>
There are three main ways to pass variables:
Using a form button using $_POST variables to pass the content
(generally best when you also have user input).
Using an HTML anchor link to pass the variables through $_GET
Using a SESSION variable that can be accessed on all pages on your site.
Using SESSION variables is the more secure way, but it the data isn't secret use the $_GET method.
To store something in a SESSION variable you need to use:
start_session();
$_SESSION['varname'] = value;
on the following page, you can read your SESSION variable just by using it's name. For example:
start_session();
echo $_SESSION['varname'];

Code is not displaying database information from query

I am trying to build a staff page, which quesries the MySQLi database holding registered users, and displays only moderators, admins, and super admins. This is the code I have. For some reason, nothing shows up in the table on the page. I have no fatal erros, so the code is "technically" correct, however the logic isn't outputting what I want.
The code below should query the database, fetch the row of info as an array, output the username and registration date into the table, and keep looping until there are now more rows left. Though, as I said, nothing is output. I have no idea what I am doing wrong.
If it makes a difference, this is a custom page in myBB forum software. I know the page is setup correctly because everything displays, except the info I am attempting to pull form the database.
<?php
global $headerinclude, $header, $theme, $footer, $lang;
if(!$mybb->user['uid'])
{
error_no_permission();
}
$lang->load('modcp');
$mysqli = new mysqli("XXXXXXXXX","XXXXXXXXXXX","XXXXXXXXX","XXXXXXXX");
$query_result = $mysqli->query("SELECT uid,username,usergroup,regdate FROM mybb_users ORDER BY regdate ASC");
if ($db->num_rows($query_result) > 0)
{
$usertablerows = "";
while($users = mysqli_fetch_row($query_result))
{
if($users['usergroup'] != 3 || $users['usergroup'] != 4 || $users['usergroup'] != 6)
{
$pass = "true";
}
else
{
$staffuseruid = $users['uid'];
$rawregdate = $users['regdate'];
$usergroupvalue = $users['usergroup'];
$staffusername = $users['username'];
$staffuser = get_user($staffuserid);
$usertablerows .= ' <tr>
<td class="trow1">' . build_profile_link($staffusername, $staffuserid). '</tf>
<td class="trow2">' . my_date($mybb->settings['dateformat'], $rawregdate). '</td>
</tr>';
}
}
}
$template='<html>
<head>
<title>'.$pages['name'].'</title>
{$headerinclude}
</head>
<body>
{$header}
<table border="0" cellspacing="1" cellpadding="2" class="tborder">
<tr><td class="thead" colspan="4"><strong>The Staff</strong></td></tr>
<tr>
<td class="tcat"><span class="smalltext"><strong>Username</strong></span></td>
<td class="tcat"><span class="smalltext"><strong>Registered</strong></span></td>
</tr>
{$usertablerows}
</table>
{$footer}
</body>
</html>';
mysqli_close($mysqli);
$template=str_replace("\'", "'", addslashes($template));
add_breadcrumb($pages['name']);
eval("\$page=\"".$template."\";");
output_page($page);
?>
You can check by appending database name to table name in mysql query.

Categories