gpt4 book ai didi

php - undefined variable ?

转载 作者:行者123 更新时间:2023-11-29 05:40:47 27 4
gpt4 key购买 nike

我在第 15 行和第 21 行收到 $id 变量的 undefined variable 错误,有人可以解释为什么吗?我看不出问题出在哪里。

<?php
function userIsLoggedIn()
{
if (isset($_POST['action']) and $_POST['action'] == 'login')
{
if (!isset($_POST['email']) or $_POST['email'] == '' or
!isset($_POST['password']) or $_POST['password'] == '')
{
$GLOBALS['loginError'] = 'Please fill in both fields';
return FALSE;
}
$password = md5($_POST['password'] . 'chainfire db');

if (databaseContainsAuthor($_POST['email'], $password, $id))
{
include 'db.inc.php';
session_start();
$_SESSION['loggedIn'] = TRUE;
$_SESSION['email'] = $_POST['email'];
$_SESSION['password'] = $password;
$_SESSION['id'] = $id;
return TRUE;
}
else
{
session_start();
unset($_SESSION['loggedIn']);
unset($_SESSION['email']);
unset($_SESSION['password']);
unset($_SESSION['id']);
$GLOBALS['loginError'] = 'The specified email address or password was incorrect.';
return FALSE;
}
}
if (isset($_POST['action']) and $_POST['action'] == 'logout')
{
session_start();
unset($_SESSION['loggedIn']);
unset($_SESSION['email']);
unset($_SESSION['password']);
unset($_SESSION['id']);
header('Location: ' . $_POST['goto']);
exit();
}
session_start();
if (isset($_SESSION['loggedIn']))
{
return databaseContainsAuthor($_SESSION['email'], $_SESSION['password'], $_SESSION['id']);
}
}
function databaseContainsAuthor($email, $password, $id)
{
include 'db.inc.php';

$email = mysqli_real_escape_string($link, $email);
$password = mysqli_real_escape_string($link, $password);

$sql = "SELECT COUNT(*) FROM author
WHERE email='$email' AND password='$password'";
$result = mysqli_query($link, $sql);

if (!$result)
{
$error = 'Error searching for author.';
include 'error.html.php';
exit();
}
$row = mysqli_fetch_array($result);

$sql = "SELECT id FROM author
WHERE email='$email'";
$id = mysqli_query($link, $sql);
if (!$id)
{
$error = 'Error searching for id.';
include 'error.html.php';
exit();
}

if ($row[0] > 0)
{
return TRUE;
}
else
{
return FALSE;
}
}

变量$id定义在databaseContainsAuthor($email, $password, $id)中,然后存储在$_SESSION['id'] session 如此自然 $id = mysqli_query($link, $sql); 应该已经通过了,但事实并非如此?

最佳答案

在函数内更改(或定义)的变量不会影响脚本的其余部分。例如:

<?php
function changeVariabe($person) {
$person = 'Bob';
}
$person = 'Alice';
changeVariable($person);
echo "Hello $person!"; // Outputs: Hello Alice!

这可以通过引用传递变量来避免,如下所示:

<?php
function changeVariabe(&$person) {
$person = 'Bob';
}
$person = 'Alice';
changeVariable($person);
echo "Hello $person!"; // Outputs: Hello Bob!

你也可以使用全局变量,像这样:

<?php
function changeVariabe() {
global $person;
$person = 'Bob';
}
$person = 'Alice';
changeVariable();
echo "Hello $person!"; // Outputs: Hello Bob!

关于php - undefined variable ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6968095/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com