2012-12-04 19 views
1

我想創建一個圖片發送一個特定的值綁定到該圖像時點擊一個PHP文件,將作出一個MySQL查詢。有一個圖像發送信息時,單擊變量爲mySQL查詢

例如,假設我有一個動物圖片的HTML頁面,當點擊一個特定的動物圖像時,比如說一張Cat的圖像,它會發送一個值作爲一個值,然後將其分配給一個變量一個MySQL查詢,將從包含貓,狗,馬等動物數據庫中提取不同品種的貓。

//animals.html 
<form action="animalQuery.php" method="get"> <input type="image" src="Cat.jpg" name="cats" width="350" height="225"> 
<form action="animalQuery.php" method="get"> <input type="image" src="Dog.jpg" name="dogs" width="350" height="225"> 

當Cat.jpg圖像被點擊我要發送的值「貓」來分配:

所以在HTML頁面,animals.html,我使用此代碼創建圖像至$動物變量,以便它基本上使得低於$語句等同於「從動物中選擇*其中品種=‘貓’;」這是一個工作查詢

//animalQuery.php 
$animal=$_GET["cats"]; 
$stmt="select * from Animals where breeds = $animal;"; 

它的工作原理,如果我硬編碼的$語句用「貓」或「狗」代替變量$ animal,所以我知道查詢是有效的我只是無法弄清楚如何點擊圖像時發送特定的值我想要的變量$動物。一旦我明白了這一點,我應該能夠弄清楚如何讓單個變量$ animal被設置爲某個值,當點擊多個圖像中的一個時,以便一個變量適用於所有圖像。

回答

2

爲什麼一個如此簡單的成熟的表單?

<a href="animalQuery.php?animal=cat"><img src="..." /></a> 
<a href="animalQuery.php?animal=dog"><img src="..." /></a> 
+0

謝謝。這正是我正在尋找的。簡單直接。我之前使用過鏈接,但並不認爲我可以從中獲取信息,因此我轉而嘗試使用表單。我確信這就是爲什麼當我絕對認爲應該有這個問題時,我很難找到一個簡單的解決方案!選擇這個是因爲它是第一個並立即執行的,但是每個人的帖子都向我介紹了一些新的東西來研究和澄清要點。謝謝你們! – NotIllogical

0

在表單中,爲按鈕指定相同的名稱,並在PHP中捕獲值。你可以這樣做:

<form action="animalQuery.php" method="get"> 
<input type="image" src="Cat.jpg" name="animal" value="Cat" width="350" height="225"> 
<input type="image" src="Dog.jpg" name="animal" value="Dog" width="350" height="225"> 
</form> 


<?php 
//Set the possible values 
$animals = array("Cat", "Dog"); 
//Check if the form is submitted and set the value if the value exists 
$animal = isset($_GET['animal']) && 
      in_array($_GET['animal'], $animals)? $_GET['animal'] : "Not chosen"; 
0

解決您的問題的另一種方法可能是用鏈接替換您的輸入。例如:

<a href="animalQuery.php?animal=cats"><img src="Cat.jpg" width="350" height="225" /></a> 
<a href="animalQuery.php?animal=dogs"><img src="Dog.jpg" width="350" height="225" /></a> 

然後,您可以更新animalQuery.php像這樣的工作:

$animal=$_GET['animal']; 

你可以看到這個頁面上的這樣一個例子:

https://stackoverflow.com/tags

你將會看到每個標籤是鏈接,而不是輸入字段:

<a href="https://stackoverflow.com/questions/tagged/c%23" class="post-tag" title="show questions tagged 'c#'" rel="tag">c#</a> 
... 
<a href="https://stackoverflow.com/questions/tagged/java" class="post-tag" title="show questions tagged 'java'" rel="tag">java</a> 
... 
<a href="https://stackoverflow.com/questions/tagged/php" class="post-tag" title="show questions tagged 'php'" rel="tag">php</a> 

最後,您應該查看用於編寫SQL的MySQLi或PDO庫。如果有人訪問此頁面:animalQuery.php?animal=cats UNION SELECT * FROM information_schema.tables,那麼他們可能會破解您的網站。

0

我有一個類似的問題,它回來了,這是因爲一些瀏覽器發送圖像座標作爲值,而不是您指定的實際值。解決特定問題(如果您必須使用圖像輸入)的最簡單方法是包含隱藏值。

<form action="animalQuery.php" method="GET"> 
    <input type="hidden" name="animal" value="cat" /> 
    <input type="image" src="Cat.jpg" /> 
</form> 

然後檢索您的animalQuery.php文件中的值。

<?php 
$animal = $_GET['animal']; 
$stmt = "select * from Animals where breeds = '$animal';"; 
?>