这是我的PHP :(该代码能够很好地完成工作)
if(isset($_COOKIE["user"])) {
$username = $_COOKIE["user"];
$pass = $_COOKIE["password"];
$check = mysql_query("SELECT * FROM members WHERE email = '$username'")or die(mysql_error());
while ($info = mysql_fetch_array( $check ))
{
//if the cookie is present but has the wrong password, they are taken to the login page
if ($pass != $info['password'])
{
header("Location: login.php");
exit();
}
else //if the cookie is present and doesn'T have the wrong password they are shown the admin area
{
include 'header.php';
}
}
}
else //if the cookie is present and doesn'T have the wrong password they are shown the admin area
{
header("Location: login.php");
exit();
}
但稍后在同一页面上,我尝试从$ info变量访问数据,但没有任何结果。我知道我做错了什么,但无法弄清楚是什么......
<?php print $info['name']?>
如果我将变量设为全局变量,我该如何使用它?
$check = mysql_query("SELECT * FROM members WHERE email = '$username'")or die(mysql_error());
$info = mysql_fetch_array( $check );
while ($info.....???)
{
}
答案 0 :(得分:2)
while ($info = mysql_fetch_array( $check ))
{
//
// do things with info:
//...
//
}
当它超出最后一条记录时,最后的$ info为false(不再记录)。因此$ info为false,while循环终止,其中没有数据库“info”。
$info0 = false;
while ($info = mysql_fetch_array( $check ))
{
if(! $info0)
{
$info0 = $info;
}
//
// do things with info:
//...
//
}
在while循环后使用 $ info0 而不是$ info。
<?php echo $info0['name']; ?>
答案 1 :(得分:0)
$ info变量已本地化为if语句。
将$ info变量设为全局。
答案 2 :(得分:0)
在while
循环后,使用mysql_data_seek函数:
$info = mysql_data_seek($check, 0) ? mysql_fetch_array($check) : null;
当然,you MUST avoid to use all PHP functions that begin with mysql_。
答案 3 :(得分:0)
如果你想在$info
中使用if(isset($_COOKIE["user"])) {
是可以的,但是如果你想在$info
之外使用if(isset($_COOKIE["user"])) {
则会出现问题,因为$info
没有初始化在if(isset($_COOKIE["user"])) {
之前,所以你的代码就像这样
$username = $_COOKIE["user"];
$pass = $_COOKIE["password"];
if(isset($_COOKIE["user"])) {
$check = mysql_query("SELECT * FROM members WHERE email = '$username'")or die(mysql_error());
while ($info = mysql_fetch_array( $check ))
{
//if the cookie is present but has the wrong password, they are taken to the login page
if ($pass != $info['password'])
{
header("Location: login.php");
exit();
}
else //if the cookie is present and doesn'T have the wrong password they are shown the admin area
{
include 'header.php';
}
}
}
else //if the cookie is present and doesn'T have the wrong password they are shown the admin area
{
header("Location: login.php");
exit();
}
$check = mysql_query("SELECT * FROM members WHERE email = '$username'")or die(mysql_error());
$info = mysql_fetch_array( $check );