我试图回显动态php标题,取决于seo的页面ID。
首先,我所有的页面都包括 header.php
这就是我的header.php
开始方式:
include("database.php");
//connect tables in order to echo out titles
//1- connect to categories table if isset get category_id
if (isset($_GET["category_id"])) {
$query = $handler->query("SELECT * FROM categories WHERE category_id = ".$_GET['category_id']." ");
while($r = $query->fetch()) {
$title = $r["title"];
}
}
//2- connect to articles table if isset get article_id
if (isset($_GET["article_id"])) {
$query = $handler->query("SELECT * FROM articles WHERE article_id = ".$_GET['article_id']." ");
while($r = $query->fetch()) {
$title = $r["title"];
}
}
//3- connect to users table if isset get user_id
if (isset($_GET["user_id"])) {
$query = $handler->query("SELECT * FROM users WHERE user_id = ".$_GET['user_id']." ");
while($r = $query->fetch()) {
$title = $r["username"];
}
}
在我随意回显如下标题后:
<title><?php if (isset($_GET["category_id"])) { echo $title; echo " |"; }
if (isset($_GET["article_id"])) { echo $title; echo " |"; }
if (isset($_GET["user_id"])) { echo $title; echo " |"; } ?> mypage.com</title>
*
结果是:
category.php?category_id=1
页面标题上的标题是:“类别1 | mypage.com”
article.php?article_id=1
页面标题上的标题是:“第1条| mypage.com”
users.php?user_id=1
页面标题上的标题是:“用户名1 | mypage.com”
*
我的问题是,我想知道我是否以此结构超载数据库?
当我打开时users.php?user_id=1
,php仍然执行此代码吗?:
//1- connect to categories table if isset get category_id
if (isset($_GET["category_id"])) {
$query = $handler->query("SELECT * FROM categories WHERE category_id = ".$_GET['category_id']." ");
while($r = $query->fetch()) {
$title = $r["title"];
}
}
还是因为我if (isset($_GET["category_id"])) {
一开始就在使用而未连接到数据库并且数据库没有超载?
看起来还可以,但是要摆脱太多条件,我建议您采用另一种方法。在每个页面上生成标题,将其分配给变量(在包含header.php之前),然后简单地回显标题。
这是一个例子:
category.php:
<?php
require_once"database.php";
if(isset($_GET["category_id"])) {
$query = $handler->query("SELECT * FROM categories WHERE category_id = ".$_GET['category_id']." ");
while($r = $query->fetch()) {
$title = $r["title"];
}
} else {
// redirect somewhere else
}
include"header.php";
?>
<body>
Content goes here
</body>
</html>
header.php:
<!DOCTYPE html>
<html>
<head>
<title><?php echo $title;?></title>
</head>
对其他文件也是如此。即您的users.php文件将如下所示:
<?php
require_once"database.php";
if (isset($_GET["user_id"])) {
$query = $handler->query("SELECT * FROM users WHERE user_id = ".$_GET['user_id']." ");
while($r = $query->fetch()) {
$title = $r["username"];
}
} else {
// redirect somewhere else
}
include"header.php";
?>
<body>
Content goes here
</body>
</html>
header.php文件将保持不变。由于服务器不需要查找多个条件,并且代码也变得更加简洁,因此可以确保节省一些服务器资源。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句