我正在學習PHP/MySQL,同時在Web應用程序上工作。部分應用程序要求從名爲「htdocs/full」的圖像目錄回顯隨機圖像。除了'first_name''last_name'的列之外,數據庫保存標題爲'image_path'的列中每個圖像的路徑。如何從PHP中隨機抽取MySQL圖像?
我可以讓它從數據庫中調用一個隨機的行,我可以讓它顯示來自'first_name'和'last_name'列的文字數據。但我努力使它從'image_path'列轉換成圖像而不是文字。
我在過去的24小時裏一直在嘗試一些方法,但是我在Stack和Google上看到的大多數其他方法都是直接從目錄中提取圖像而不使用數據庫行(它由於相應的'first_name'和'last_name')。
這裏是我到目前爲止(雖然我也有許多不同的變化,這個我覺得是我來最接近):
<?php
$username="root";$password="*********";$database="offenders";
mysql_connect('localhost',$username,$password);
mysql_select_db($database) or die("Unable to select database");
$sSQLQuery = "SELECT image_path FROM offenders ORDER BY RAND() LIMIT 1";
$aResult = mysql_query($sSQLQuery);
WHILE($aRow = mysql_fetch_array($aResult)):
{
header("Content-Type:image/jpeg");
echo "<img src='php/imgView.php?imgId=".$aRow['image_path']."' />";
}
ENDWHILE;
?>
它生成一個網頁,在一個破碎的圖像左上方。我已經嘗試過使用$ aRow以及$ aRow ['image_path']的回顯,以及其他一些似乎會導致錯誤的調整。任何想法我做錯了什麼?
非常感謝!
更新代碼:
<?php
$username="root";$password="*******";$database="offenders";
mysql_connect('localhost',$username,$password);
mysql_select_db($database) or die("Unable to select database");
$src="full/";
//if you have any problem in the solution check this line,
//means weather you are providing right path for your files or not.
$sSQLQuery = "SELECT image_path FROM offenders ORDER BY RAND() LIMIT 1";
$aResult = mysql_query($sSQLQuery);
$aRow = mysql_fetch_array($aResult);
$file_path=$src.$aRow["image_path"];
//echo "<a href='php/imgView.php?imgId=".$aRow['image_path']."'>"."<img src=".$file_path." />"."</a>".'<br/>';
echo "<img src=".$file_path." />".'<br/>';
//echo "<img src=full/1b2ba2f9a8b8ee9c062b09767535d69bd954e125.jpg>";
/* if(isset($_GET['imgId']))
{
//i am query only first_name but you can add for field as you want
//and i also used $_get['imgId']; in the query which is not safe but you can make it for //secure.
$sSQLQuery = "SELECT first_name FROM offenders where image_path='".$_GET['imgId']."'";
$aResult = mysql_query($sSQLQuery);
WHILE($aRow = mysql_fetch_array($aResult)):
{
echo $aRow['first_name'];
}
ENDWHILE;
}
*/
?>
你怎麼看,當你查看從Web瀏覽器生成的HTML源? – iWantSimpleLife 2014-09-03 01:02:19
Ack。添加適當的標籤:<!DOCTYPE HTML>
確定。從你的來源看,PHP似乎是正確的。我想你應該檢查你的imgView.php tp確保它正確地發送圖像數據。 – iWantSimpleLife 2014-09-03 03:46:56