2012-05-20 66 views
3

我一直試圖在最近幾天試圖理解如何從多個表中獲取數據,但我不能說我完全理解它是如何工作的。無論如何:)從多個mysql表使用php獲取圖像

我想要做的是使用搜索欄獲取存儲在多個表中的圖像來定義參數,即藝術家的名字(我知道在數據庫中存儲圖像可能會導致許多問題,但它的一個爲大學鍛鍊,所以我真的不能做太多的工作)

所以要具體了。我有5個表稱爲animaldata,cardata,landscapedata,peopledata和其他數據。每張表格都有以下字段:1個id 2個artist_name 3個細節4個照片5個phototype和6個日期。如果artist_name是上傳圖像的登錄人員的姓名,並且細節是標題,則照片是要保存的斑點項目,並且照片類型是圖像的良好類型:P

所以我想要做的是當某人使用搜索欄搜索藝術家時,代碼將獲取並顯示藝術家上傳的所有表格中的所有圖像。

下面是我用來從1個表中獲取數據的代碼,但我不知道如何改變它以便搜索其他表。

這是search.php中

<?php 
mysql_connect ("localhost","root","") or die (mysql_error()); 
mysql_select_db ("photo_album_db"); 

$term = $_POST['term']; 

$sql = mysql_query("select * from animaldata where artist_name like '%$term%'"); 

while ($row = mysql_fetch_array($sql)){ 
    echo $row['details']; 
echo "</br>"; 
echo "<img src=getan.php?id=".$row['id']." width=250 height=200/>"; 
echo "</br>"; 
} 
?> 

搜索欄的格式如下:提前 <form action="search.php" method="post"><input type="text" name="term" /><input type="submit" name="search" value="Search" /></form>

感謝您的任何建議,如果你需要更多的「蛛絲馬跡」讓我知道:) :) :)

+4

**你的代碼很容易受到SQL注入**你真的* *應使用準備好的語句,在其中傳遞您的變量作爲參數並不會得到SQL評估。 。如果你不知道我在說什麼,或者如何解決它,請閱讀[Bobby Tables](http://bobby-tables.com)的故事。 – eggyal

+1

如果他的教授嘗試向他注入SQL注入,我發誓我會飛到那裏,嗨! –

+0

哈哈哈,真好! – ekptwtos

回答

2

試試這個:

// set up database connection ... 

$term = my_awesome_sanitizer($_POST['term']); 

$tables = array("animaldata", "cardata", "landscapedata", "peopledata", "otherdata"); 
foreach ($tables as $table) 
{ 
    $sql = mysql_query("select * from $table where artist_name like '%$term%'"); 
    while ($row = mysql_fetch_array($sql)) 
    { 
     echo $row['details']; 
     // show stuff .... 
    } 
} 
+0

現在做了這個工作!感謝你們! :D你真的很有幫助! – ekptwtos

+0

這使得5個單獨的查詢到數據庫,至少**工會加入**所有的查詢,以便他們將一次全部發送。 –

+1

@Mihai有效的觀點,但是OP正試圖理解基礎知識,而且這個解決方案更容易理解和維護,性能損失很小。 –

2

爲了改變表,如果他們有相同的列然後使用:

$sql = mysql_query("select animaldata.artist_name AS animaldata_artist_name, cardata.artist_name AS cardata_artist_name /* do this for all columns in all tables, or mor specifically for the columns you need */ from animaldata AS a, cardata AS c, landscapedata AS l, peopledata AS p where a.artist_name like '%$term%' OR c.artist_name like '%$term%' OR l.artist_name like '%$term%' OR p.artist_name like '%$term%'"); 

試試這個用於顯示圖像:

<img src="data:image/jpeg;base64,".base64_encode($row['image_blob'])." width... 

這並不會使照片中的單獨的請求。它會將圖像的內容嵌入到HTML中。

該技術由data:uri協議支持。

+0

謝謝,我改變了這些東西,但當我搜索藝術家的名字,只是一個空白頁面沒有任何內容(但也沒有錯誤)出現 – ekptwtos

+0

如果你正在運行linux試試「php -l/path/to/file .php「來檢查語法/解析錯誤。 –

+0

如果您直接訪問的文件(http://example.com/page.php)具有它們,則不會顯示語法/解析錯誤。只有包含文件時纔會顯示它們。 –