Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP从MySQL查询切换页面_Php_Mysql_Switch Statement_Case - Fatal编程技术网

PHP从MySQL查询切换页面

PHP从MySQL查询切换页面,php,mysql,switch-statement,case,Php,Mysql,Switch Statement,Case,我有以下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':

我有以下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;
}
}

另外,您不能在运行时动态定义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”
文件。

为什么不在MySQL中进行过滤,例如从id=XXX的页面中选择*,这样您就只能得到一条记录?把整个表都放到php中,然后扔掉除了一条记录以外的所有记录是绝对没有意义的。你不能在一个开关里放一段时间。只有大小写可以是内部命令。案例x:也应该使用常量值。如何添加else语句?对于旧代码,如果$pg不存在,则包含错误文件<代码>默认值:如果(文件_存在(“error.php”){include(“error.php”);}