我有以下PHP代码:
//switch
if (isset($_GET['pg']))
$pg = $_GET['pg'];
else{
$pg = 'home';
}
switch ($pg){
case 'home':
if (file_exists("pages/home.php")){
include("pages/home.php");}
break;
case 'about':
if (file_exists("pages/about.php")){
include("pages/about.php");}
else{include_once("error.php");}
break;
case 'products':
if (file_exists("pages/products.php")){
include("pages/products.php");}
else{include_once("error.php");}
break;
case 'contact':
if (file_exists("pages/contact.php")){
include("pages/contact.php");}
else{include_once("error.php");}
break;
default:
if (file_exists("error.php")){
include("error.php");}
}
?>如何通过MySQL查询进行此切换?我尝试过这样的方法,但不幸的是不起作用:
$SQLquery = "SELECT * FROM pages";
$result = mysql_query($SQLquery);
switch ($pg){
while($row = mysql_fetch_array($result)) {
case $row['id']:
include($row['id'].'.php');
break;
}
}发布于 2013-01-16 05:01:06
AFAIK,则不能在运行时动态定义switch语句。这些控制结构是在代码运行之前被解析的,并且不能在以后被修改(如果我错了,请纠正我)。
我会尝试一些类似的东西:
while($row = mysql_fetch_array($result)) {
if($row['id'] == $pg){
include($row['id'].'.php');
break;
}
}编辑:再想一想,@Marc M发表的关于这个问题的评论的解决方案要好得多。执行以下操作:
$SQLquery = "SELECT * FROM pages WHERE id='" . $pg ."';";
$result = mysql_query($SQLquery);
if($row = mysql_fetch_array($result))
include($row['id'].'.php');
else
include("error.php");既然您希望已经将MySQL列id声明为UNIQUE,那么您要么恰好得到一行,要么您的"error.php"文件将被包括在内。
https://stackoverflow.com/questions/14346628
复制相似问题