2013-01-15 85 views
0

切換頁面,我有以下的PHP代碼:PHP從MySQL查詢

//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; 
} 
} 
+3

爲什麼你不會在mysql中進行過濾,例如'從ID = XXX'的頁面選擇*,所以你只能得到一個記錄?在將整個桌面吸收到php中,然後扔掉除了一個記錄以外的所有內容都是絕對沒有**的。 –

+0

你不能在開關內放置一段時間。只有情況可以是內部命令。案例x:也應該使用常數值。 – cgTag

回答

2

AFAIK,你不能在運行時動態定義switch語句。這些控制結構在代碼運行之前被解析,並且以後不能更改(如果我錯了,請糾正我)。

我想嘗試的東西沿着這行:

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


編輯:關於第二個想法,解決@Marc中號公佈關於這一問題的評論是更好的方式。這樣做:

$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列idUNIQUE,你要麼exaclty一行或您的"error.php"文件將被包括在內。

+0

我如何添加一個else語句?對於舊代碼,如果$ pg不存在則包含錯誤文件。 (默認: if(file_exists(「error.php」)){include(「error.php」);}' – CBuzatu