0
我創建一個食譜書(只是堅持練習使用數據庫)顯示圖像,並再次,我堅持...crreating函數從數據庫中的存儲路徑
我已經能夠顯示圖像,但在一個糟糕的方式(我認爲)... 我迄今所做的:
在我的index.php:
$recipes = get_recipes();
$attachments = get_attachments();
$attachments_paths = get_image_path();
echo '<h2>recipes</h2>';
echo '<table id="recipesTable" border="1">';
echo '<tr>';
echo '<th>Recipe ID</th>';
echo '<th>Recipe Name</th>';
echo '<th>Attachment ID</th>';
echo '<th>Attachment path</th>';
echo '<th>Attachment image</th>';
echo '</tr>';
foreach ($recipes as $recipe) {
echo '<tr>';
echo '<td>' . $recipe['id'] . '</td>';
echo '<td>' . $recipe['name'] . '</td>';
echo '<td>' . $recipe['attachment_id'] . '</td>';
foreach ($attachments_paths as $attachment_path) {
if ($recipe['attachment_id'] === $attachment_path['id']) {
echo '<td>' . $attachment_path['attachment_path'] . '</td>';
}
}
echo '<td>' . echo display_image(); . '</td>';
echo '</tr>';
}
echo '</table>';
的functions.php:
function get_recipes() {
include'db_connection.php';
try {
return $conn->query("SELECT * FROM recipes");
} catch (PDOException $e) {
echo 'Error:' . $e->getMessage() . "<br />";
return array();
}
return true;
}
function get_attachments() {
include'db_connection.php';
try {
return $conn->query("SELECT * FROM attachments");
} catch (PDOException $e) {
echo 'Error:' . $e->getMessage() . "<br />";
return array();
}
return true;
}
function get_image_path() {
include 'db_connection.php';
$sql = 'SELECT recipes.name, attachments.id, attachments.attachment_path FROM attachments LEFT JOIN recipes ON recipes.attachment_id=attachments.id';
try {
$results = $conn->prepare($sql);
$results->execute();
} catch (PDOException $e) {
echo 'Error: ' . $e->getMessage() . '<br />';
return array();
}
return $results->fetchAll(PDO::FETCH_ASSOC);
}
function display_image() {
foreach($attachments as $attachment) {
$file = $attachment['attachment_path'];
return '<img src="' . $file . '" />';
}
} 欄目的 「食譜」 表: ID,名稱,創建時間,來源,categories_id,attachment_id,chef_id
列在 「附件」 表: ID,attachment_path,recipe_id
而且還提到,我保存的路徑圖像爲: http://localhost/cooking_book/images/mistique.jpeg
如果有更好的方法來做到這一點,請讓我知道!因此,正如你所看到的,我的display_image()根本不起作用,我知道foreach循環在那裏什麼也沒有做。我只是沒有任何想法我可以做,任何建議將不勝感激:)
HTML源代碼如何不符合您的期望? –
您不應該存儲完整的網址,這會使您的設置非常不靈活。例如,如果域名更改?還是基本的佈局,以便它不再是'/ images /'? – arkascha
我知道!或多或少,我知道......我昨天讀了它,我試了很多次用dirname(__ FILE__)來做,但我在一段時間後感到沮喪......我應該用dirname得到真實的路徑(__FILE__)對不對? –