所以,我知道我的代码正在工作,我已经尝试撤消所有步骤以查看错误在哪里,但我仍然不断收到错误
我的 PHP ID = 0。
你们能告诉我如何修复我的代码吗?
错误如下:
未定义的变量list_id。它适用于我的本地机器,但不适用于 上传到服务器。
谢谢。
以下是我的代码:
if(!empty($_GET['id'])){
$list_id = intval(($_GET['id']));
try {
$sql = 'SELECT * FROM items where id =' . $list_id;
$query = $pdo->prepare($sql);
$query->execute();
} catch(Exception $e) {
echo $e->getMessage();
die();
}
$list = $query->fetch(PDO::FETCH_ASSOC);
if ($list == FALSE) {
header("location: index.php");
}
}
if ($list_id == 0) {
header("location: index.php");
}
这里似乎有几个问题。我已经添加了内联注释。
if(!empty($_GET['id'])){
$list_id = intval($_GET['id']); //was double parenthesis here
try {
$sql = 'SELECT * FROM items where id =' . $list_id;
$query = $pdo->prepare($sql);
$query->execute();
} catch(Exception $e) {
echo $e->getMessage();
die();
}
$list = $query->fetch(PDO::FETCH_ASSOC);
$count = count($list); //count result and use for comparison instead of false
if ($count === 0) {
header("location: index.php");
exit;
}
} else {
header("location: index.php"); //if no $_GET, redirect
exit;
}
您
需要做的就是实例化变量$list_id
:
$list_id = 0; // <-- HERE
if(!empty($_GET['id'])){
$list_id = intval(($_GET['id']));
...
...
如果没有
id
参数,您似乎要重定向到索引。由于您已经检查了它是否存在,因此请在 else
子句中重定向。删除最后一个块并添加:
else
{
header("location: index.php");
exit;
}
您可能还希望在 if
块中的 header()
调用之后添加exit;
,以便不会执行使用数据库的代码。