简体   繁体   English

PHP从MySQL查询切换页面

[英]PHP switching pages from a MySQL query

I have the following PHP code: 我有以下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");}
}
?>

How can I do this switch by a MySQL query? 如何通过MySQL查询进行此切换? I tried something like this, but unfortunately doesn't work: 我尝试了类似的方法,但不幸的是它不起作用:

$SQLquery = "SELECT * FROM pages";
$result = mysql_query($SQLquery);

switch ($pg){
while($row = mysql_fetch_array($result)) {
    case $row['id']:
        include($row['id'].'.php');
        break;
}
}

AFAIK, you cannot dynamically define switch statements at runtime. AFAIK,您不能在运行时动态定义switch语句。 These control structures are parsed before the code is run and can't be altered later (correct me if I'm wrong). 这些控制结构在代码运行之前已解析,以后无法更改(如果我错了,请纠正我)。

I'd try something along the lines of this: 我会尝试一些类似的方法:

while($row = mysql_fetch_array($result)) {
    if($row['id'] == $pg){
        include($row['id'].'.php');
        break;
    }
}


EDIT: On second thought, the solution @Marc M posted as a comment on the question is way better. 编辑:经过深思熟虑,作为对问题的评论发布的解决方案@Marc M更好。 Do this: 做这个:

$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");

And since you hopefully have declared the MySQL column id as UNIQUE , you either get exaclty one row or your "error.php" file will be included. 而且,由于您希望将MySQL列id声明为UNIQUE ,因此您可能只获得了一行,否则将包括"error.php"文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM