0

这应该是一个简单的 PHP mySQL 问题(我假设它有点像 PHP 和 mySQL 101,但我找不到答案)...

我有一个我创建的注册表单,当填写完表单并将其提交到 register_user.php 页面时。该页面上的代码是这样的:

<?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");
?>

如您所见,它重定向到一个名为 profile.php 的页面。在 profile.php 上,我试图通过以下方式回显会话变量:

<?php echo "Hello". $_SESSION['firstname']; ?>

我假设变量在从 register_user.php 重定向到 profile.php 时失去了它的价值(至少这是我迄今为止从我的研究中收集到的)。我想我必须session_start();在 profile.php 上再次声明变量,但我不知道如何将变量设置为适当的值。在 register_user.php 中,我能够使用上一页表单中的 post 值,但是当它重定向到 profile.php 时,我不能再这样做了。

有人可以解释我如何在 profile.php 上检索这些值吗?(我再次觉得这是一个非常基本的问题,但我仍在学习,所以要温柔哈哈 :))

4

3 回答 3

1

您正在使用单引号$_POST,因此您的值未应用,$_SESSION并且您在里面缺少引号

$_POST['value']
-------^-----^

$_SESSION['firstname'] = $_POST['firstname'];

并且始终session_start();在页面顶部声明,当然您需要session_start();在其他页面上声明,然后才能回显会话值

此外使用mysqli_()代替mysql_()

于 2012-10-27T06:32:08.550 回答
0

您根本没有使用转义数据,哈哈。尝试使用 PDO(或 mysqli <-- i 在末尾)和准备好的语句来避免 SQL 注入。

于 2012-10-27T06:35:30.500 回答
0

我会将您注册表单中的 session_start() 命令放在页面顶部,因为我的感觉(我自己是初学者,所以请耐心等待)是它实际上没有考虑任何注册过程。

I've always been told that the session start command itself should always happen at the beginning of the page, so before you even start the registration form code. Then on the next page you are redirecting to you should also start with session_start at the top of the page.

于 2013-10-10T11:57:34.230 回答