我正在创建一本食谱书(只是为了继续练习数据库),再一次,我被困了......
我能够显示图像,但是方式不好(我认为)...... 到目前为止我做了什么:
在我的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 . '" />';
}
} &#34;食谱&#34;的列表: id,name,created,duration,source,categories_id,attachment_id,chef_id
&#34;附件&#34;的列表: id,attachment_path,recipe_id
还提到,我保存了图像的路径: http://localhost/cooking_book/images/mistique.jpeg
如果有更好的方法,请告诉我!
所以,正如你所看到的,我的display_image()根本不起作用,我知道foreach循环在那里什么也没做......我只是没有其他任何想法,我可以做,任何建议将不胜感激:))
答案 0 :(得分:0)
嗯,我确信这不是最好的方法,我会继续努力,但至少,我现在正在显示图像;
这个功能可以更基本......
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() {
include 'db_connection.php';
return $image_path = get_image_path();
}
为了显示它,在index.php上,我刚刚在我的表中添加了另一个字段:
echo '<td>';
foreach ($images as $img) {
echo '<img class="attachment" src="' . $img['attachment_path'] . '"/>';
}
echo '</td>';
但是,如果有人建议选择更好的选项,请告诉我们:)