I am trying to render uploaded image from Mysql to frontend in a file called result.php
This is the code that uploaded the image to Mysql
include ('connect.php');
//if button with the name uploadfilesub has been clicked
if(isset($_POST['uploadfilesub'])) {
//declaring variables
$filename = $_FILES['uploadfile']['name'];
$filetmpname = $_FILES['uploadfile']['tmp_name'];
//folder where images will be uploaded
$folder = 'imagesuploadedf/';
//function for saving the uploaded images in a specific folder
move_uploaded_file($filetmpname, $folder.$filename);
//inserting image details (ie image name) in the database
$sql = "INSERT INTO `uploadedimage` (`imagename`) VALUES ('$filename')";
$qry = mysqli_query($conn, $sql);
if( $qry) {
echo "</br>image uploaded";
}
}
?>
The uploaded images are saved on a folder on my server called imagesuploadedf
I used this code below to render the image on the result.php but it's showing the file name only, I need the image to be rendered.
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = 'SELECT * from uploadedimage';
if (mysqli_query($conn, $sql)) {
echo "";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
$count=1;
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) { ?>
<tbody>
<tr>
<td>
<?php echo $row['imagename']; ?>
</td>
</tr>
</tbody>
<?php
$count++;
}
} else {
echo '0 results';
}
?>
</table>
What do I need to write on result.php to show/render the uploaded image on the page?
You should write an HTML page containing <img> elements referring to the images you want to display.
It might look like this:
<td>
<?php
$imgTag = '<img src="/imagesuploadedf/' . $row['imagename'] . '" />';
echo $imgTag; ?>
</td>
This puts out stuff like this into your web page.
<td>
<img src="/imagesuploadedf/image_file_name"/>
</td>
If your web page is coming from https://images.example.com this will make the browser download the image at https://images.example.com/imagesuploadedf/image_file_name from your server and display it in the page.
Related
I have this code where i write comment in a textarea field and select a picture and sumbit to mysqli database through php, but the problem im having is when i only select a picture to upload or when i write a comment/texts in the textarea and select a picture to upload it works but then when i only write comment/texts in the textarea field and submit it doesn't work.
And also i want to create a comment reply "quote" , like to click reply on a comment then quote and reply the comment.
// My compose form
<form method="post" action="process.php" enctype='multipart/form-data'>
<textarea class="text-area" cols="75" name="comment" type="text" rows="5" placeholder="write message"></textarea><br>
<input type='file' style="width:257px" name='fileToUpload' ><br>
<input class="submitButton" type='submit' value='Send'>
</form>
// My process.php code
<?php
// start username session
session_start();
//connect to database
require_once ("dtb.php");
$commentSenderName = $_SESSION['username'];
$date = date('Y-m-d H:i:s');
$comment = isset($_POST['comment']) ? htmlspecialchars($_POST['comment']) : "";
//Directory where to upload file
$name = $_FILES['fileToUpload']['name'];
$target_dir = "upload/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
//Select file type
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
//Valid file extensions
$extensions_arr = array("jpg","jpeg","png","gif","NULL");
//Check extension
if( in_array($imageFileType,$extensions_arr) ){
//Upload file
move_uploaded_file($_FILES['fileToUpload']['tmp_name'],$target_dir.$name);
//Insert data into tables
$sql = "INSERT INTO tblcomment(comment,comment_sender_name,date,image) VALUES ('". $comment . "','" . $commentSenderName . "','" . $date . "','".$name."')";
$result = mysqli_query($conn, $sql);
if (! $result) {
$result = mysqli_error($conn);
}
echo "<p style='padding-left:22px;padding-top:10px;font-family:verdana;font-size:20px'> Post entered... </p>";
header("Refresh: 3; url=mysite.com");
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
// This is the code that fetches and display data from mysql database
$sql = "SELECT comment_sender_name,date,comment,image FROM tblcomment";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
//output data of each row
while($row = mysqli_fetch_assoc($result)) {
$name = $row['comment_sender_name'];
$time = $row['date'];
$msg = $row['comment'];
$img = $row['image'];
$now = array("<span><b style='font-size:25px'> $name </b></span>","<span style='font-size:14px;color:#474747;padding-left:40px;'><i>$time</i></span>");
$message = "<p style='color:#232323;font-size:20px;font-weight:bold'> $msg </p>";
$image_src = "<a href='#'><img src='upload/$img' style='width:550px;height:320px;border-radius:5px'></img></a>";
echo '<table border="0" style="padding-left:25px;box-sizing;height:450px;width:400px;">
<tr>
<td>' .$now[0] .$now[1] .$message .$image_src. "<br/><br/><br/><br/>". '</td>
</tr>';
}
} else {
echo "<p style='padding-left:22px'> 0 results </p>";
}
//Free result set
mysqli_free_result($result);
?>
Im not getting any kind of error.
Aside from my comment above with the many, many vulnerabilities in your code, the issue looks like you assume you always have a $_FILES. If you didn't upload a file, $_FILES['fileToUpload']['name']; is not going to exist. Check for it with if (isset($_FILES['fileToUpload'])) { and act on that information appropriately. You probably did get an error, or more specifically a warning, but it is in your web servers log file.
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>";
}
}
}
Handling file uploads
I create php script that shows the Id and the image stored in mysql database, but i can just see the image without the Id, how can i show the image and the id in this php script ?
<?php
$con = mysqli_connect("localhost","root","","othmane") or die(mysqli_error($con));
if($_SERVER['REQUEST_METHOD']=='GET'){
$id = $_GET['id'];
$sql = "SELECT image,image_type FROM images where id = $id";
$r = mysqli_query($con,$sql) or die(mysqli_error($con));;
$result=mysqli_fetch_array($r);
header('Content-Type:image/jpeg');
$ss=$result['image_type'];
if ($ss == 'php') {
echo 'Type of image ' . $result['image_type'];
echo ( $result['image']);
} else if ($ss == 'android') {
echo 'Type of image ' . $result['image_type'];
echo base64_decode( $result['image'] );
}
mysqli_close($con);
}
?>
this is what i get when i execute script :
note : when i remove echo 'Type of image ' . $result['image_type']; from the code the image is properly displayed. but i want to show the image and its type too.
I need to upload and retrieve image from a database, I am able to store the image in the database but unable to display it later. please help
I wrote the following code to retrieve from the database.
$result1=mysql_query("INSERT INTO userdata(id, username, firstname, lastname, imageType, image)VALUES('', '" . $_SESSION['username'] . "', '" . $_SESSION['firstname'] . "', '$lastname','{$image_size['mime']}','{$imgData}')") or die("Invalid query: " . mysql_error());
if($result1)
{
echo "</br>";
echo "Registration successful";
echo "</br>";
echo $lastid=mysql_insert_id();//get the id of the last record
echo "uploaded image is :"; ?>
<img src="imageView.php?image_id=<?php echo $lastid; ?>" /><br/>
<?php
echo "</br>";
}#if result1into db successful
else
{
echo $result1;
echo "Problem in database operation";
imageView.php has the following code:
<?php
$conn = mysql_connect("localhost", "root", "");
mysql_select_db("wordgraphic") or die(mysql_error());
if(isset($_GET['id'])) {
$sql = "SELECT imageType,image FROM userdata WHERE id=". $_GET['image_id'];
$result = mysql_query("$sql") or die("<b>Error:</b> Problem on Retrieving Image BLOB<br/>" . mysql_error());
$row = mysql_fetch_array($result);
header("Content-type: " . $row["imageType"]);
echo $row["image"];
}
mysql_close($conn);
?>
What could be possibly wrong with the code?
When i try to run imageView.php with static id image is getting displayed. So i guess the error is in passing the variable is this code:
echo "uploaded image is :"; ?>
<img src="imageView.php?image_id=<?php echo $lastid; ?>" /><br/>
<?php
what could be possibly wrong?
just a smal rectification
<img src="imageView.php?image_id=<?php echo $lastid; ?>" />
instead of this
src = src path where u r saving the image file lets say in images folder that would be here $imagedata store the file name in the DB so that you can retreive it from the image folder
<img src="images/$imgData" width="your wish" height="your wish"/>
I want to display uploaded image to a different page showing first name last name and image corresponding to that upload this is the code I have it currently displaying all the images save on a folder I just want to display the recent uploaded image corresponding to the information submitted
<?php
$con = mysql_connect("localhost","username","pa…
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("database", $con);
$sql="INSERT INTO nametable (fname, lname, mname, image, status, id)
VALUES
('$_POST[fname]','$_POST[mname]','$_PO… 'display','')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "";
mysql_close($con);
?> <?php
// Assigning value about your server to variables for database connection
$hostname_connect= "localhost";
$database_connect= "database";
$username_connect= "username";
$password_connect= "password";
$connect_solning = mysql_connect($hostname_connect, $username_connect, $password_connect) or trigger_error(mysql_error(),E_USER_ERROR…
#mysql_select_db($database_connect) or die (mysql_error());
if($_POST)
{
// $_FILES["file"]["error"] is HTTP File Upload variables $_FILES["file"] "file" is the name of input field you have in form tag.
if ($_FILES["file"]["error"] > 0)
{
// if there is error in file uploading
echo "Return Code: " . $_FILES["file"]["error"] . "
";
}
else
{
// check if file already exit in "images" folder.
if (file_exists("images/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{ //move_uploaded_file function will upload your image.
if(move_uploaded_file($_FILES["file"]["t… . $_FILES["file"]["name"]))
{
// If file has uploaded successfully, store its name in data base
$query_image = "insert into table";
if(mysql_query($query_image))
{
echo "Stored in: " . "images/" . $_FILES["file"]["name"];
}
else
{
echo'';
}
}
}
}
}
?>
<html>
<head>
</head>
<body>
<p>First name: <?php echo $_POST["fname"]; ?><br></p>
<p>Middle name: <?php echo $_POST["mname"]; ?><br></p>
<p>Last name: <?php echo $_POST["lname"]; ?><br></p>
</form>
</body>
</html>
<?php
// Assigning value about your server to variables for database connection
$hostname_connect= "localhost";
$database_connect= "database";
$username_connect= "username";
$password_connect= "password";
$connect_solning = mysql_connect($hostname_connect, $username_connect, $password_connect) or trigger_error(mysql_error(),E_USER_ERROR…
#mysql_select_db($database_connect) or die (mysql_error());
$query_image = "SELECT * FROM table";
// This query will show you all images if you want to see only one image pass id='$id' e.g. "SELECT * FROM nametable id='$id'".
$result = mysql_query($query_image);
if(mysql_num_rows($result) > 0)
{
while($row = mysql_fetch_array($result))
{
echo '<img width="165" height="104" border="0" src="images/'.$row["image"].'">';
}
}
else
{
echo 'File name not found in database';
}
?>
$query_image = "SELECT * FROM table order by id desc limit 1";