[英]Need some PHP assistance
how do i tell this php code that, when there's not a ?page=randompage in the url, it will trow the active to index.php automatically? 我如何告诉这个php代码,当URL中没有?page = randompage时,它将自动将活动代码拖到index.php吗?
<?php
$query = "SELECT pagename, pagetitle FROM pages LIMIT 8";
$result = $mysqli->query($query);
echo "<ul>";
while ($row = $result->fetch_array(MYSQLI_ASSOC)){
echo "<li><a href=\"?page=".$row["pagename"]."\"";
if ($_GET['page'] == $row['pagename']) {
echo " class=\"active\""; } echo "> ".$row["pagetitle"]." </a></li>";
}
echo "</ul>";
?>
It's beacuse whenever my url looks like this http://localhost/greencph/
it shows a php error, because it does not know which site it is on, it works perfect as long as the url looks like this: http://localhost/greencph/?page=index.php
a detailed explanation on how to fix this problem would be appreciated! 这是因为每当我的URL看起来像这样的
http://localhost/greencph/
它就会显示php错误,因为它不知道它在哪个站点上,因此只要URL看起来像这样,它就可以完美运行: http://localhost/greencph/?page=index.php
有关如何解决此问题的详细说明,将不胜感激!
Please remember i'm a idiot, explain to me so i understand it. 请记住我是个白痴,向我解释,以便我理解。 xD
的xD
The error is coming because, every time the value of $_GET
is not getting set. 因为每次没有设置
$_GET
的值,都会出现错误。
So, to deal with it, 因此,要处理它,
get the value of $_GET['page']
in a variable. 在变量中获取
$_GET['page']
的值。
So that, if we do not get $_GET
, we will assign it a default value, that is index page. 因此,如果没有得到
$_GET
,我们将为其分配一个默认值,即索引页。
$page = ! empty($_GET['page']) ? $_GET['page'] : 'index'; // set default value.
And change this line: 并更改此行:
if ($page == $row['pagename']) {
So, the final modified code should be: 因此,最终的修改后的代码应为:
<?php
$query = "SELECT pagename, pagetitle FROM pages LIMIT 8";
$result = $mysqli->query($query);
$page = ! empty($_GET['page']) ? $_GET['page'] : 'index';
echo '<ul>';
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$class = '';
if ($page == $row['pagename']) {
$class = 'active';
}
echo '<li><a href="?page='.$row["pagename"].'" class="'.$class.'">' . $row["pagetitle"].' </a></li>';
}
echo "</ul>";
?>
Use the $_GET
array: 使用
$_GET
数组:
<?php
if(isset($_GET['page'])) {
// Your code
...
}
?>
Problem is in this line 问题在这条线
if ($_GET['page'] == $row['pagename']) {
You're not checking whether the index 'page' even exists. 您无需检查索引“页面”是否存在。 So, when you try to load the page without any GET parameters
$_GET['page']
won't be even set and you'll get an error for accessing unset element. 因此,当您尝试在没有任何GET参数的情况下加载页面时,甚至都不会设置
$_GET['page']
并且在访问unset元素时会出现错误。
To fix this simply check 要解决此问题,只需检查
if(isset($_GET['page']) {
...your code...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.