Here are the following scripts I have created. first is the form that allows to select an image to be displayed. Second is the display page. My question is how can I display images from my form using a database/table in php?? I only want to display a single image that I have selected using the select file form.
<!DOCTYPE html>
<html>
<body>
<form action="display.php" method="post" enctype="multipart/form-data">
Select image to display:
<input type="file" name="fileToDisplay" id="fileToDisplay">
<input type="submit" value="Display Image" name="submit">
</form>
</body>
</html>
This is the second script
<?php
$db = mysqli_connect("localhost","root", "", "myDB");
$sql = "SELECT * FROM images";
$result = mysqli_query($db, $sql);
while ($row = mysqli_fetch_array($result)){
echo "<img src=' images/". $row['image']."' >";
echo "<p>". $row['text']."</p>";
echo "</div>";
}
The simplest way of doing this is to upload the image to the server and save the image name in your database.
Uploading the image to the server and saving to the database
// display.php
$tmp_file = $_FILES['fileToDisplay']['tmp_name']; // get the temp name of the image
$name = $_FILES['fileToDisplay']['name']; // get the name of the image
Now you need to move the file to a directory on your server with move_uploaded_file() and save the name of the file in the database.
move_uploaded_file($tmp_file, 'images/' . $name)
$remove_extension = explode('.', $name);
$sql = "INSERT INTO `images`(`image`, `text`) VALUES ('$name', '$remove_extension[0]')";
Complete code
// display.php
$tmp_file = $_FILES['fileToDisplay']['tmp_name'];
$name = $_FILES['fileToDisplay']['name'];
if (move_uploaded_file($tmp_file, 'images/' . $name)) {
$remove_extension = explode('.', $name);
$sql = "INSERT INTO `images`(`image`, `text`) VALUES ('$name', '$remove_extension[0]')";
if (mysqli_query($db, $sql)) {
$last_id = $db->insert_id;
$sql = "SELECT * FROM images WHERE id = $last_id";
$result = mysqli_query($db, $sql);
while ($row = mysqli_fetch_array($result)){
echo "<div><img src=' images/". $row['image']."' >";
echo "<p>". $row['text']."</p>";
echo "</div>";
}
}
}