开发者

Page including with mysql in php

I have a nice page including system here is the code for it

 if(isset($HTTP_GET_VARS['mod']))
 {
 $page = $HTTP_GET_VARS['mod'];
 }
 else
 {
 $page = 'home';
 }

 switch($page)
 {

         case 'home':
         require('home.ph开发者_StackOverflowp');
         break;


         default:
         echo('Error: There is no file on this server with that name');
         }


          }

I am trying to get the case, require from a DB called pages there are 2 fields Name, Link i am trying to get all of the results from the table so it will display the pages


It's not particularly clear from your question, but my reading of it is that you want a way to check any value of $page against a link value in a db table (pages?), without having to write all possible values in to your switch statement,

If my understanding is correct, then the below is a quick-and-dirty function which should let you do this. In a live, heavily-trafficed environment you'd obviously need to build in caching so every page load doesn't hit the db, and strong input validation, neither of which are in the demo below, but this should at least give you an idea of where to go next.

Common library file:

/**
 * Given a page name, see if we have an associated
 * link in the db.
 * If so, return the link value, else false
 */
function getTemplate($page)
{
    // Check db to see if we have a link for this page
    // On heavy-traffic sites, this should be cached out 
    $query = sprintf("SELECT link FROM pages WHERE name = '%s'",
            mysql_real_escape_string($page));
    $result = mysql_query($query, $db_cnx);

    // Have we any results?
    if (mysql_num_rows($result) > 0)
    {
        // Assumption: 'name' is unique in the db
        $row = mysql_fetch_assoc($result);
        return $row['link'];
    }
    else
    {
        return false;
    }
}

Header.php:

include('common.lib.php');
if(isset($HTTP_GET_VARS['mod']))
{
    $page = $HTTP_GET_VARS['mod'];
}
else
{
    $page = 'home';
}

// Check whether our page has a link in the db
$template = get_template($page);

if($template)
{
    require( $template );
}
else
{
    // Got false back from get_template, no link found
    echo('Error: There is no file on this server with that name');
}


$server_db = "YOUR_SERVER_DB";
$user_db = "YOUR_USER_DB";
$password_db = "YOUR_PASSWORD_DB";
$db_name = "YOUR_DB_NAME";
$table = "YOUR_TABLE_NAME";

$link = mysql_connect($server_db,$user_db,$password_db);
if (!$link) {
  die('Could not connect: ' . mysql_error());
}
mysql_select_db($db_name);
$sql = sprintf("select Name, Link from %s",$table);
$rs = mysql_query($sql,$link);
while($row = mysql_fetch_assoc($rs)) {
    echo "<a href='".$row['Link']."'>".$row['Name']."</a>";
}
mysql_free_result($rs);
mysql_close($link);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜