I'm trying to save my images to a folder inside the root folder and the name of the image in the database. Now, how am I going to retrieve the specific image for the particular id
?
In my codes, I can only retrieve all the images but I only want one image base on his id
and image_name
Is that possible?
Here is my codes:
Here is the codes for uploading the image
to the folder and the image_name
to the database:
<?php
include '../session.php';
require_once 'config.php';
if (isset($_POST['submit'])) {
$img_dir = "../updated_photo/";
$target_file = $img_dir . basename($_FILES["image"]["name"]);
$imageName = $_FILES["image"]["name"];
$imageData = file_get_contents($_FILES["image"]["tmp_name"]);
$imageType = $_FILES["image"]["type"];
if (substr($imageType, 0,5) == "image") {
$query = "UPDATE `crew_info` SET `image_name` = ? WHERE `id` = ?";
$stmt = mysqli_prepare($conn, $query);
mysqli_stmt_bind_param($stmt, 'si', $imageName, $_POST['id']);
mysqli_stmt_execute($stmt);
file_put_contents($target_file, $imageData);
$id = $_POST['id'];
header("Location: ../admin/view_all_info.php?id=$id");
}
else {
echo "Image not Uploaded!";
}
}
?>
Below is the code for retrieving the image
and the image_name
<?php
include '../session.php';
require_once 'config.php';
if (isset($_REQUEST['id'])) {
$query = "SELECT `id`, `image_name` FROM `crew_info` WHERE `id` = ?";
$stmt = mysqli_prepare($conn, $query);
mysqli_stmt_bind_param($stmt, 'i', $_REQUEST['id']);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $id, $image_name);
while (mysqli_stmt_fetch($stmt)) {
echo sprintf("%s", $image_name);
}
$img_dir = "../updated_photo/";
$images = glob($img_dir."*.jpg");
foreach ($images as $img) {
echo '<img src="'.$img.'" />';
}
}
else {
echo "No Image";
}
?>
In my retrieving code, I've tried to use if statement
instead of foreach
like the code below
if (count($images) > 0) {
$img = $images[0];
echo '<img src="'.$img.'" />';
}
This statement will fetch all the jpg photos from that directory
$img_dir = "../updated_photo/";
$images = glob($img_dir."*.jpg");
foreach ($images as $img) {
echo '<img src="'.$img.'" />';
}
If you want to display just one photo you can do this after getting image_name from database
$img_dir = "../updated_photo/";
$img_path = $img_dir.$image_name;
echo '<img src="'.$img_path.'" />';
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.