我有一个页面,是查询数据库相当多次使用php与重复;查询块之间也散布着HTML。例如
<?php
--code here--
SELECT DISTINCT `Retailer`
FROM `product`
WHERE `Product` = 'iPad 2'
--continue code here--
?>
html content here
<?php
--code here--
SELECT DISTINCT `Brand`
FROM `product`
WHERE `Product` = 'iPad 2'
--continue code here--
?>
重复几次。查询所在的该页需要复制到其他页面,但"Product"行必须更改(例如,Product
= 'iPhone')。目前,每个查询都位于单独的php代码块内,所以我必须去每个地方,它被引用来改变它。有没有可能在文档的顶部设置一个我可以更改的位置?如果有,我该怎么做?
我个人喜欢使用$_GET
变量来做这样的事情,使用mod_rewrite
来生成不包括变量的必要url。我假设您的一些html也会随着查询的WHERE
行而更改。您可以尝试这样做:
产品页面链接
<ul>
<li><a href="products/index.php?product=ipad2">iPad 2</a></li>
<li><a href="products/index.php?product=iphone4s">iPhone 4S</a></li>
</ul>
products/index.php文档
<?php
$product = $_GET['product'];
//various code
$retailer_result = mysql_query("SELECT DISTINCT Retailer FROM product WHERE Product = '$product'");
//more code
//define and require the html document
$product_page_dir = "products/pages/";
$product_page_path = $product_page_dir . $product;
require $product_page_path;
//more various code
$brand_result = mysql_query("SELECT DISTINCT Brand FROM product WHERE Product = '$product'");
//the rest of the code
这是使用此方法的最简单方法。不要忘记在进行任何查询之前建立连接MySQL并选择数据库。还要记住,您可能还应该包括错误处理。注意:上面的代码是未经测试的。
你的意思可能是写一些类似function
的东西,你可以重用:
function get_product($column, $name) {
return db("SELECT DISTINCT `$column` FROM `product` WHERE `Product` = ?", $name);
}
然后在页面顶部设置一个变量$product_name
,并重用它来发出查询。(如果你是这个意思的话)
$product_name = "iPad 2";
...
get_product("Retailer", $product_name);
...
get_product("Brand", $product_name);
...
get_product("Price", $product_name);