This should be an easy PHP mySQL question (I’m assuming it’s sort of PHP and mySQL 101 but I’m having trouble finding an answer)…
I have a registration form I’ve created and when the form is filled out and submitted it posts to a register_user.php page. The code on that page is this:
<?php
$con = mysql_connect("my_host","my_username","my_password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
// username and password sent from form
//NEVER Remove the mysql_real_escape_string. Else there could be an Sql-Injection!
$firstname=mysql_real_escape_string($_POST['firstname']);
$lastname=mysql_real_escape_string($_POST['lastname']);
$email=mysql_real_escape_string($_POST['email']);
$password=mysql_real_escape_string($_POST['password']);
$sql="INSERT INTO my_table (firstName, lastName, email, password)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[email]', '$_POST[password]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
session_start();
// Register $myusername, $mypassword and redirect to file "profile.php"
$_SESSION['firstname']='$_POST[firstname]';
$_SESSION['lastname']='$_POST[lastname]';
$_SESSION['email']='$_POST[email]';
$_SESSION['password']='$_POST[password]';
header("location:profile.php");
?>
As you can see, it redirects to a page called profile.php . On profile.php I’m trying to echo out the session variables by saying:
<?php echo "Hello". $_SESSION['firstname']; ?>
I’m assuming the variable loses it’s value upon the redirect from register_user.php to profile.php (at least this is what I gather from my research thus far). I’m thinking I have to use session_start(); on the profile.php to declare the variables again but I don’t know how to set the variables to the appropriate values. In register_user.php I was able to use the post values from the form on the previous page but by the time it redirects to profile.php I can no longer do that.
Can someone please explain how I can retrieve those values on profile.php? (again I have a feeling this is a very basic question but I’m still learning so be gentle haha 🙂 )
You are using single quote around
$_POSTand hence your values are not applied to$_SESSIONand you were missing quotes insideAnd always declare
session_start();on the top of the page and ofcourse you need to declaresession_start();on the other page before you echo out the session valueMoreover use
mysqli_()instead ofmysql_()