Can't display data in my php sessions - php

I'm having a problem with my sessions forms. It's probably a simple answer but I can't seem to figure it out.
My html:
<body>
<h1>Hobby Selection Page<br /></h1>
<form method="post" action="page1.php" id="hobbies" >
<p>
<label for="Name">Name: </label>
<input type="text" id="name" name="name"/>
</p>
<p>What is your favorite thing to do?<br/>
<select name="hobby">
<option value="movies">Movies</option>
<option value="read">Reading</option>
<option value="music">Music</option>
<option value="other">My hobby is not listed here</option>
</select>
<br/><br/>
<input type="submit" value="Submit Form"/> <input type="reset" value="Clear Form"
/>
</p>
</form>
</body>
First php page (page1.php):
<?php
session_start();
echo 'Click the link below';
$_SESSION['name'] = " . name . ";
$_SESSION['hobby'] = " . hobby . ";
// Second page
echo '<br />page 2';
?>
Second php page (page2.php):
<?php
// page2.php
session_start();
echo 'Your favorite activity:<br />';
echo $_SESSION['name'];
echo $_SESSION['hobby'];
echo '<br />page 1';
?>
My aim is to input data from the first html page and then send it to the first php page (to recieve the session variables) and then to be directed to the second php page where it should retrieve the session variables and display the input data I have entered/selected. I am able to get the html and php pages to display and be linked from one page to the next but I am unable to display (in first php page) the data I have inputted from the html page.

your first page1.php should be like this.
<?php
session_start();
echo 'Click the link below';
$_SESSION['name'] = $_POST['name'];
$_SESSION['hobby'] = $_POST['hobby'];;
// Second page
echo '<br />page 2';
?>
You are not getting data because you are storing string in $_SESSION not the text you entered in fields.

In page1.php
Replace
$_SESSION['name'] = " . name . ";
$_SESSION['hobby'] = " . hobby . ";
By
$_SESSION['name'] = $_POST['name'];
$_SESSION['hobby'] = $_POST['hobby'];

You're missing a few things. First give your submit button a name, like this:
<input type="submit" value="Submit Form" name="my_submit" />
Then, on page1.php, change this:
$_SESSION['name'] = " . name . ";
$_SESSION['hobby'] = " . hobby . ";
To something like this:
// Check if form was submitted. If so, get inputs.
if (isset($_POST['my_submit'])) {
$_SESSION['name'] = $_POST['name'];
$_SESSION['hobby'] = $_POST['hobby'];
}
That should get you started in the right direction. Later, you can add some validation to ensure that $_POST['name'] and $_POST['hobby'] are filled in correctly before assigning them to the $_SESSION

Related

Send PHP form data to a different page

I have just written this code in which I have a form. You have to write your name, surname and country. You also have to choose your favourite colour. After that, you push a submit button so that you can see the data afterwards. I'm using the GET method with 1 page, but I have to use a second one with the POST method so that each echo is on that second page.
How could I do that? My code is:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Form</title>
<link rel="stylesheet" type="text/css" href="form.css">
</head>
<body>
<section>
<?php
if (isset($_GET["name"])){
$name = $_GET["name"];
if ($name != ""){
$surname = $_GET["surname"];
$country = $_GET["country"];
$colour = $_GET["colour"];
echo "<p>";
echo "<h2>Data</h2>";
echo $name . " " . $surname . "</br />";
echo $country . "<br />";
echo $colour;
echo "</p>";
}else
echo "<strong>Complete the blank spaces</strong>";
}else{
?>
<h1>Form</h1>
<form class="elegant" method="GET" action="?">
<fieldset>
<legend>Favourite colour</legend>
<div>
<label for="nombre">Name</label>
<input type="text" placeholder="Name" name="name"
id="name" />
</div>
<div>
<label for="surname">Surname</label>
<input type="text" placeholder="Surname" name="surname"
id="surname" size="50" />
</div>
<div>
<label for="country">Country</label>
<input type="text" placeholder="Country" name="country" id="country"
size="10" maxlength="9" />
</div>
<div>
<select name="colour" id="colour">
<option value="yellow" <?php if ($colour == "yellow" ) echo "selected" ?> >yellow</option>
<option value="red" <?php if ($colour == "red" ) echo "selected" ?> >red</option>
</div>
<input class="btn" type="submit" value="Save" />
</fieldset>
</form>
<?php
}
?>
</section>
</body>
</html>
I know i have to use a link to that second page, but that's all I know. Thanks in advance!
If I understand correctly, the code you show is for Page 1 where the user can:
Input data if data don't exist;
View data and confirm them if they exist. At this point store data in SESSION and send the user to an other page.
To do so, remember you have to add the session_start() command right at the beginning of every page in which you will be able to manipulate Session Data.
<?php
session_start();
if (isset($_GET["name"])){
$name = $_GET["name"];
if ($name != ""){
$surname = $_GET["surname"];
$country = $_GET["country"];
$colour = $_GET["colour"];
echo "<p>";
echo "<h2>Data</h2>";
echo $name . " " . $surname . "</br />";
echo $country . "<br />";
echo $colour;
echo "</p>";
$_SESSION["name"] = $name;
$_SESSION["surname"] = $surname;
$_SESSION["country"] = $country;
$_SESSION["colour"] = $colour;
Confirm
}else
echo "<strong>Complete the blank spaces</strong>";
}else{
?>
...
In "another_page.php" then you will find that you can access your data simply querying the $_SESSION array.
<?php
session_start();
...
// Echo session variables that were set on previous page
echo "Name is " . $_SESSION["name"] . ".<br>";
echo "Surname is " . $_SESSION["surname"] . ".";
// etc.
?>
Complete reference is the PHP Manual and simple reference is in W3C PHP Sessions page.
In the form tag you can specify where to form gets submitted to:
<form class="elegant" method="GET" action="YOUR_PAGE_URL_HERE">
On that second page you get the values via the $_GET Variable like
<?php
echo $_GET['name'].' '.$_GET['surname'];

Trouble updating phpmyadmin DB

Database values not updating
Working on a web form here. I want to update user info in a database. Using AJAX to pull from a list and generate information. When “Update Information” is clicked, the database should update the given values. I am just testing it on “FirstName” for now. The Code runs and I get no errors, but my database is not updating.
Process.php:
<body>
<?php
if (!isset($_SESSION['email']))
Header ("Location:logout.php") ;
if(isset($_POST['submit'])){
$NewFirstName = trim($_POST['NewFirstName']);
$StudentPID = $_POST['ca'];
$sql = "update Student SET FirstName=".$NewFirstName."where StudentPID = ".$StudentPID."";
$PleaseUpdate = mysql_query($sql);
//echo "<script type='text/javascript'>alert('Data was successfully inserted')</script>";
}
?>
<form name="input" action="process.php" method="post">
Ajax Demo
<br/><br/>
Select a Student: <br/><br/>
<select name="ca" onchange="showDetail(this.value)">
<?php print GetCategory(); ?>
</select>
<div id="txtHint"><b>Person info will be listed here.</b></div>
<?php ?>
<br />
<input type="submit" name = "submit" value="Update Information">
</form>
<br/><br/>
Logout
</body>
</html>
GetDetail.php:
<?php session_start(); //this must be the very first line on the php page, to register this page to use session variables
//if this is a page that requires login always perform this session verification
require_once "inc/sessionVerify.php";
require_once "dbconnect.php";
if (!isset($_SESSION['email']))
Header ("Location:logout.php") ;
$q = $_GET['q']; //get the values passed from this query string
$sql = "select * from Student where StudentPID = '".$q."'";
$result = $DB->GetAll($sql);
//display the result in a table
print '<br /><br /><span style="color:red">Data retrieved from database:</span><br/ >';
//get the rows
$i = 0; //This is used to remember how many checkboxed created in total
foreach ($result as $row)
{
//Now make the form
print( '<form action="getDetail.php" method="post">
First Name: <input type="text" id="NewFirstName" name="NewFirstName" value='.$row["FirstName"].'><br>
Last Name: <input type="text" id="" name="" value='.$row["LastName"].'><br>
</form>
');
}
print '</table>';
?>

how to pre populate fields based on search results of data base

I am new to stack overflow and really appreciate all the help. I currently have a database with basic columns, name id company etc. I created a search query that shifts through this list based on firstname, lastname, or timestamp date. I was able to print the results on the query page of the search but want this to pre populate on the same form page as a new entry. i was able to link from the query page to the form page but am not sure how to populate these results on the form page.
my current query page prints as the following :
<!DOCTYPE html>
<html>
<head>
<title>
</title>
</head>
<body>
<div id="container" style="width:750px;background-color:#FFFE8D;margin-left: 250px">
<div id="Back" style="float:left; background-color:#FFFE8D;">
<form action="http://localhost/contractor/existingcontractorpage3.php">
<input type="submit" value="Back">
</form>
</div>
<div id="Is this the Contractor?" style="float:right; background-color:#FFFE8D;">
<form action="http://localhost/contractor/redirectcontractorpage.php">
<input type="submit" value="Next">
</form>
</div>
<div id="info" style="width:750px;height:95px; text-align: center">
<h3> If this is the contractor, please move on to the next page using the corresponding button above. </h3>
<h3> Please enter the exact information on the next page. </h3>
</div>
<div id="results" style="width:750px;height:225px; text-align: center">
<?php
$host = "localhost"; //server
$db = ""; //database name
$user = ""; //databases user name
$pwd = ""; //password
mysql_connect($host, $user, $pwd) or die(mysql_error());
mysql_select_db($db) or die(mysql_error());
$searchTerm = trim($_GET['searchname']);
// Check if $searchTerm is empty
if($searchTerm == "")
{
echo "Enter name you are searching for.";
exit();
}
else
{
$sql = "SELECT * FROM contractor WHERE CONCAT(FIRSTNAME,' ',LASTNAME,' ', ARRIVAL) like '%$searchTerm%'";
$query = mysql_query($sql);
$count=mysql_num_rows($query);
if(($count)>=1)
{
$output = "";
while($row = mysql_fetch_array($query))
{
$output .= "First Name: " . $row['FIRSTNAME'] . "<br />";
$output .= "Last Name: " . $row['LASTNAME'] . "<br />";
$output .= "Arrival: " . $row['ARRIVAL'] . "<br />";
}
echo $output;
}
else
echo "There was no matching record for the name " . $searchTerm;
}
?>
</div>
<br> </br>
<br> </br>
</body>
</html>
Now ideally i would want the results to pop up here, and if possibly have a radio button to the right of each result( if there is ever more than one) to select and continue to the form page to pre populate each field. the form page is simply like this:
<form action="insert_submit.php" method="post">
First Name: <input type = "text" name="FIRSTNAME" id="FIRSTNAME" />
<br>
</br>
Last Name: <input type = "text" name="LASTNAME" id="LASTNAME"/>
<br>
</br>
Purpose: <input type = "text" name="PURPOSE" id="PURPOSE"/>
<br>
</br>
Company: <input type = "text" name="COMPANY" id="COMPANY" />
<br>
</br>
Who here to see: <input type = "text" name="WHOHERETOSEE" id="WHOHERETOSEE"/>
<br>
</br>
<input type="submit" value="Submit">
<br>
</br>
</form>
thanks so much! hope to hear back soon as this is my last straw on my project.
The simplest way to do this is to pull the data from the database like you're doing, except where you want to add the form into the page. Then in your loop print out form fields:
You need to give each radio a unique name. You could use an incrementing id, or you could give it the same as the row name.
Method 1:
while($row = mysql_fetch_array($query))
{
$output .= "<label>First Name: " . $row['FIRSTNAME'] . "</label><input type=\"radio\" name = \"radio[]\" value=\"".$row['FIRSTNAME']." ".$row['LASTNAME']."\"/>";
..
..
}
You will then be able to get the values from the radio buttons by using GET or POST when the from is submitted.
Setting name = "radio[]" puts all the values in an array which you can get on the next page once the form is submitted.
On the next page after form submission, $_POST['radio'] or $_GET['radio'] will return an array of all the values which you specify. Notice how the value attribute has been filled in above. Do this for each of the rows.
Also be careful about using my_sql connections. It's depreciated as of PHP 5.5.0. Use mysqli or PDO instead, it's more secure. http://ie1.php.net/function.mysql-connect
Check it this link. it compares and provides examples on both
I don't see where you're connecting the query search and form page, but you could create the link back containing the data in GET params in the url, since I don't see password or private material in these fields. Then use php to populate the forms.
$url = "your_form_page?";
while($row = mysql_fetch_array($query))
{
$url .= "fname=" . $row['FIRSTNAME'];
$url .= "&lname=" . $row['LASTNAME'];
$url .= "&arrival=" . $row['ARRIVAL'];
}
// $url = your_form_page?fname=bob&lname=jones&arrival=blah
Then to populate the form..
<form action="insert_submit.php" method="post">
First Name: <input type = "text" name="FIRSTNAME" id="FIRSTNAME" value="<?php echo $_GET['fname']; ?>" />
Hopefully this helps or at least gets you thinking in the right direction.

HTML/PHP Survey not passing to MySQL database properly

I'm trying to make a small survey that populates the selections for the dropdown menu from a list of names from a database. The survey does this properly. I want to submit the quote the user submits with this name into a quote database. The quote text they enter into the field goes in properly, however, the name selected from the menu does not get passed in. Instead I get a blank name field.
I understand some of my code is out of context, but the name is the only thing that does not get passed in properly.
On form submit, I include the php file that submits this data to the database:
<form action="<?php $name = $_POST['name']; include "formsubmit.php";?>" method="post">
<label> <br />What did they say?: <br />
<textarea name="quotetext" rows="10" cols="26"></textarea></label>
<input type="submit" value="Submit!" />
</form>
The variable $name comes from this (which populates my dropdown menu):
echo "<select name='name'>";
while ($temp = mysql_fetch_assoc($query)) {
echo "<option>".htmlspecialchars($temp['name'])."</option>";
}
echo "</select>";
And here is my formsubmit.php:
<?php:
mysql_select_db('quotes');
if (isset($_POST['quotetext'])) {
$quotetext = $_POST['quotetext'];
$ident = 'yankees';
$sql = "INSERT INTO quote SET
quotetext='$quotetext',
nametext='$name',
ident='$ident',
quotedate=CURDATE()";
header("Location: quotes.php");
if (#mysql_query($sql)) {
} else {
echo '<p> Error adding quote: ' .
mysql_error() . '</p>';
}
}
?>
Your form action stuff looks weird, but regardless, I think the problem you're having has to do with not setting $name = $_POST['name'] like you're doing with $quotetext = $_POST['quotetext']. Do that before the sql statement and it should be good to go.
edit to try to help you further, I'll include what the overall structure of your code should be, and you should tweak it to fit your actual code (whatever you're leaving out, such as setting $query for your name options):
file 1:
<form action="formsubmit.php" method="post">
<label> <br />What did they say?: <br />
<textarea name="quotetext" rows="10" cols="26"></textarea></label>
<select name='name'>
<?php
while ($temp = mysql_fetch_assoc($query)) {
echo "<option>".htmlspecialchars($temp['name'])."</option>";
}
?>
</select>
<input type="submit" value="Submit!" />
</form>
formsubmit.php:
<?php
mysql_select_db('quotes');
if (isset($_POST['quotetext'])) {
$quotetext = $_POST['quotetext'];
$name = $_POST['name'];
$ident = 'yankees';
$sql = "INSERT INTO quote SET
quotetext='$quotetext',
nametext='$name',
ident='$ident',
quotedate=CURDATE()";
if (#mysql_query($sql)) {
header("Location: quotes.php");
} else {
echo '<p> Error adding quote: ' .
mysql_error() . '</p>';
}
}
?>
echo "<select name='name'>";
while ($temp = mysql_fetch_assoc($query)) {
$nyme = htmlspecialchars($temp['name']);
echo "<option value='$nyme'>$nyme</option>";
}
echo "</select>";-
This way you will receive the value of the name in $_POST array
and you have to get that value out of $_POST array as well you need to change the
code add the following line to get the name in your script.
$name = $_POST['name'];
you need to change the form action tag
<form action='formsubmit.php' .....>
and in that file after successful insertion you can redirect the user to whereever.php.
so it was fun explaining you every thing bit by bit change this now in your code as well.
if (#mysql_query($sql)) {
header("Location: quotes.php");
} else {
echo '<p> Error adding quote: ' .
mysql_error() . '</p>';
}

PHP Update table Inserts blank fields

UPDATE: I narrowed it down, when I got rid of this tag in the header.php file it all works, can someone please explain this.
<script src="#" type="text/javascript"></script>
Hi I'm having quite an annoying issue with my php code. I am trying to update a php database, from a form, when I do this however the fields in the data base become empty after submitting. Please Help! You can view it in action here http://andcreate.com/shoelace/admin/edit1.php click on the lists on the right to edit them and see what happens.
<?php
include("header.php");
echo "<h2>Edit Posts</h2>";
echo "<div id='editNav'>";
echo "<p>Choose Post to Edit</p>";
//////////GET ALL RECORDS AND BUILD A NAV SYSTEM FROM THEM////////
$results = mysql_query("SELECT * FROM shoeData ");
while($row = mysql_fetch_array($results)){
$id = $row['id'];
$name = $row['name'];
$about = $row['about'];
echo "$date " . substr($name, 0, 40) . " <br/> ";
}
$thisID = $_GET['id'];
if(!isset($thisID)){
$thisID = 22;
}
//////////FINISH ALL RECORDS AND BUILD A NAV SYSTEM FROM THEM////////
echo "</div>";
///////IF USER SUBMITS CHANGES UPDATE THE DATABASE//////////
//has user pressed the button
$update = $_GET['update'];
if($update == "yes") {
$name = $_POST['name'];
$about = $_POST['about'];
$company = $_POST['company'];
$buy = $_POST['buy'];
//update data for this record
$sql = "UPDATE shoeData SET
name = \"$name\",
about = \"$about\",
company = \"$company\",
buy = \"$buy\"
WHERE id= $thisID";
$thisUpdate = mysql_query($sql) or die(mysql_error());
}
///////END IF USER SUBMITS CHANGES UPDATE THE DATABASE//////////
/////////// HERE WE GET THE INFO FOR ONE RECORD ONLY////////
$results = mysql_query("SELECT * FROM shoeData WHERE id=$thisID");
while($row = mysql_fetch_array($results)){
$name = $row['name'];
$about = $row['about'];
$company = $row['company'];
$buy = $row['buy'];
}
//////////////FINISH GETTING INFO FOR ONE RECORD ONLY/////////////
?>
<form name="formS" method="post" action="<?php echo $_SERVER['PHP_SELF']."?id=$thisID&update=yes";?>">
Name
<p>
<input type="text" name="name" id="name" value="<?php echo $name;?>" />
</p>
About
<p>
<input type="text" name="about" id="about" value="<?php echo $about;?>" />
</p>
Company
<p>
<input type="text" name="company" id="company" value="<?php echo $company;?>" />
</p>
Name
<p>
<input type="text" name="buy" id="buy" value="<?php echo $buy;?>" />
</p>
<p>
<input type="submit" name="submit" id="submit" />
</p>
</form>
<p><a class="delete" href="delete.php?id=<?php echo $thisID;?>">Delete this post</a></p>
<?php
include("footer.php");
?>
You have $update = $_GET['update'];, but then right after that, you're using $_POST. A given request is either GET or POST, not both - thus whenever $_GET['update'] is set to "yes", there aren't going to be any POST vars set, and thus the update will be done with all of the values it's setting blank.
Chances are you actually meant to use either $_GET or $_POST in both places - since your updates are going through, but are blank, it sounds like you want to use $_GET (though for form submission/updates, you should probably really be using POST instead).
This may seem silly, but are you confusing $_GET and $_POST variables? You use one to check whether to enter the loop, and another to populate the string.
Also, as a minor aside, your SELECT statement towards the end of the snippet can be optimized by adding LIMIT 1 to the end of it, as presumably you're only going to be recalling one entry per id, no?

Categories