2011-11-30 25 views
0

我有一個查詢就是BEING重複使用與PHP好幾次數據庫的頁面;查詢塊也在中間插入html。一個例子是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 =「iPhone」)。目前,每個查詢都位於內單獨的PHP代碼塊,所以我必須去那裏它被引用來改變它的每個地方。是否有可能,我可以改變文檔的頂部有一個位置?如果是這樣,我該怎麼做?

回答

0

我個人比較喜歡使用$_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> 

產品/ 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和任何查詢之前選擇數據庫。另外請記住,你也應該包括錯誤處理。注意:上面的代碼未經測試。

0

你大概的意思寫的東西像function,你可以重複使用:

function get_product($column, $name) { 
    return db("SELECT DISTINCT `$column` FROM `product` WHERE `Product` = ?", $name); 
} 

然後,只需設置一個變量$product_name頂部您的網頁,並重新使用,對於issueing查詢。 (如果這就是你的意思。)

$product_name = "iPad 2"; 
... 
get_product("Retailer", $product_name); 
... 
get_product("Brand", $product_name); 
... 
get_product("Price", $product_name); 
+0

如果您打算在多個頁面中使用這樣的功能,您還需要將該功能放在單獨的文件中幷包含該文件。 您可能還希望將函數調用的結果分配給變量,並在單個HTML塊中使用變量。這會讓你清楚地分開兩者。 –