PHP从MySQL查询切换页面

I have the following PHP code:

//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? 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. 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. 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.