嘿伙计,所以我真的有一个问题在PHP,我已经工作了一个小时,我可以让它工作。所以在我的数据库中我有两个表:
usuarios和菜单
因此每个用户都有一个如下所示的菜单:
usuarios
id email .......菜单
1封电子邮件...... 1,2,3,4
其中1,2,3,4是我将爆炸并将其转换为数组的文本,因此后者我可以通过菜单检查菜单ID。
菜单
id url .....
1个档案..........
2条消息..........
3退出..........
4支持..........
我不知道为什么它不起作用,请帮忙。
<?php
if (!empty($_SESSION['id'])) {
include_once "database.php";
$section = !empty($_GET['s']);
try {
$stmt = $db->prepare("SELECT * FROM usuarios WHERE id=:usuid");
$stmt->execute(array(':usuid'=>$_SESSION['id']));}
// Checks the user id from his session (session has been already started in headers)
if($stmt->rowCount() > 0){
$row = $stmt->fetch();
$menus = $row['menus'];
//Gets the menus
$menus = explode(",", $menus);
//Converts the text into an array.
$i = 0;
$menusize = sizeof($menus);
//Checks how big is $menus array
$menusize = $menusize -1;
//This is because $i=0 and not 1
while ($i == $menusize) {
try{
$stmt = $db->prepare("SELECT * FROM menus WHERE id=:menus");
$stmt->execute(array(':menus'=>$menus[$i]));
$row = $stmt->fetch();
if ($section==$row['url']) {
echo '<li class="liselected"><a href="?s='.$row['url'].'"><i class="'.$row['icon'].'"></i><p>'.$row['name'].'</p></a></li>';
}else{
echo '<li class="menuelement"><a href="?s='.$row['url'].'"><i class="'.$row['icon'].'"></i><p>'.$row['name'].'</p></a></li>';
}
$i++;
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}
//Here is the problem, in this while
} else {
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}else{
header("Location:index.php");
}
?>
我已经检查了,发生的事情是$我似乎没有增加,我一直在努力,但似乎什么也没做。
谢谢大家的支持!
答案 0 :(得分:3)
你应该完全不同的方式,比如将菜单存储在不同的行中但是现在:
<?php
if (!empty($_SESSION['id'])) {
include_once "database.php";
$section = !empty($_GET['s']);
try {
# When you set the $_SESSION['id'] and you're sure it's sanitized you don't have to prepare a query. Instead execute it directly.
# Preparing is useful for user submitted data or running the same query more then once with different values (seen below)
$stmt = $db->prepare("SELECT * FROM usuarios WHERE id=:usuid");
$stmt->execute(array(':usuid'=>$_SESSION['id']));
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
if($stmt->rowCount() > 0){
// This part of the code does not match your description of your database.
$row = $stmt->fetch();
$menu = explode(",", $row['menus']);
// end
$stmt = $db->prepare("SELECT * FROM menus WHERE id=:menus");
try{
foreach($menu as $value){
$stmt->execute(array(':menus'=>$value));
$row = $stmt->fetch();
$css_class = ($section == $row['url']) ? 'liselected' : 'menuelement';
echo '<li class="'.$css_class.'"><a href="?s='.$row['url'].'"><i class="'.$row['icon'].'"></i><p>'.$row['name'].'</p></a></li>';
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}
} else {
header("Location:index.php");
}
?>
请注意,我只准备了一次查询,这是正确的方法。准备工作具有服务器性能,但一旦准备就可以重新绑定值。
另外,我将循环更改为foreach循环,更易于维护。 在代码中还有一些括号问题,我的建议总是以相同的方式编码,因此很容易发现这些问题。