[英]php Notice: Undefined index: id in C:\xampp\htdocs\includes\middle.php on line 3
I am making a website and am getting thrown this error when I go to www.mydomain.org. 我正在制作一个网站,并且在访问www.mydomain.org时会抛出此错误。 This code Works when going to http://mydomain.org/index.php?id=home 要在此代码的工作 http://mydomain.org/index.php?id=home
How do I fix this as I don't want people to have to type in the /index.php?id=home 如何解决此问题,因为我不希望人们输入/index.php?id=home
<div id="middle_main">
<?php
$page = $_GET['id'];
if ($page == "") { include "pages/home.html"; }
else { include "pages/$page.html"; }
?>
</div>
Check if it is set, if not, set it to 'home': 检查是否已设置,如果未设置,则将其设置为“ home”:
$page = isset($_GET['id']) ? $_GET['id'] : 'home';
Then you don't need an if statement to check it is set: 然后,您不需要if语句来检查它是否已设置:
include "pages/$page.html";
Notices are really recent in PHP development, and they are not errors, which means you don't have to fix them. 声明实际上是PHP开发中的最新内容,它们不是错误,这意味着您不必修复它们。 Yet, this is a very good practise to do so. 但是,这是一个非常好的做法。
The undefined index
notice warns you that you are trying to read an array index that hasn't been initialised. undefined index
通知会警告您,您正在尝试读取尚未初始化的数组索引。 In your case, you try to read the home
index of the $_GET
array. 在你的情况,你尝试读取home
中的索引$_GET
数组。 When your URL is something.php?home=something
, then $_GET['home']
is initialised automatically, and no notice appears. 如果您的URL是something.php?home=something
,则$_GET['home']
将自动初始化,并且不会显示任何通知。 However, when you access something.php
, this index isn't set, which explains the notice ! 但是,当您访问something.php
,未设置此索引,这说明了注意事项!
In your code, you need to check whether this index is set, and assign it a default value when it isn't. 在您的代码中,您需要检查是否设置了该索引,并在未设置索引时为其分配默认值。
$page = isset($_GET['home']) ? $_GET['home'] : 'home';
In this case, if the home
index isn't set, $page
will be set to "home". 在这种情况下,如果未设置home
索引,则$page
将设置为“ home”。 See http://davidwalsh.name/php-shorthand-if-else-ternary-operators if you want to know more about the ternary operator (? and :) which I've just used. 如果您想了解有关我刚刚使用的三元运算符(?和:)的更多信息,请参见http://davidwalsh.name/php-shorthand-if-else-ternary-operators 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.