Displaying images from Database not working - php

I have tried a number of methods but my code still doesn't show images from the database on my website. When I click upload, I get an output of only the file name and file details but no photos are shown.
Here is my code that has to display the images.
<main>
<section align='center'>
<h1 id="rcorner2"align='center'style="font-size:30px; position:fixed;">Photo Library</h1>
<br><br>
<div class="wrapper">
<!--h2 align='left'>Photos</h2-->
<div class="photo-container">
<?php
include_once 'dbh.php';
$sql = "SELECT * FROM photos ORDER BY orderPhotos DESC";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "Error updating photo library!";
}else{
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while ($row = mysqli_fetch_assoc($result)) {
echo '<a href="#">
<div style="background-image: url(../libraries/photos/'.$row["imageFullName"].');"></div>
<h3>'.$row["filetitle"].'</h3>
<p>'.$row["filedescription"].'</p>
</a>';
}
}
?>
</div>
</div>
</section>
</main>
Connection to database
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "portal uploads";
$conn = mysqli_connect($servername, $username, $password, $dbname);
?>
And here is the database connection from the html form.
<?php
if(isset($_POST['upload'])) {
$newFileName = $_POST['filename'];
if(empty($newFileName)){
$newFileName = "photo";
}else{
//Replacing spaces in filename with underscores
$newFileName = strtolower(str_replace(" ", "-", $newFileName));
}
$filetitle = $_POST['filetitle'];
$filedescription = $_POST['filedescription'];
$file = $_FILES['file'];
$fileName = $file["name"];
$fileType = $file["type"];
$fileTempName = $file["tmp_name"];
$fileError = $file["error"];
$fileSize = $file["size"];
$fileExt = explode(".", $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array("jpg", "jpeg", "png");
//Error handling for allowed file types
if(in_array($fileActualExt, $allowed)) {
if ($fileError === 0) {
if($fileSize < 10000000) {
//Make file unique through naming
$imageFullName = $newFileName . "." . uniqid("", true) . "." . $fileActualExt;
$fileDestination = "../libraries/photos/" . $imageFullName;
include_once "dbh.php";
//Checking for error handling when fields have been left empty
if(empty($filetitle) || empty($filedescription)) {
header("location:photos_edit.php?upload=empty");
exit();
} else {
$sql = "SELECT * FROM photos;";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "SQL statement failed!";
}else{
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$rowCount = mysqli_num_rows($result);
$setPhotoOrder = $rowCount + 1;
$sql = "INSERT INTO photos (filetitle, filedescription, imageFullName, orderPhotos) VALUES (?, ?, ?, ?);";
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "SQL statement failed!";
}else{
mysqli_stmt_bind_param($stmt, "ssss", $filetitle, $filedescription, $imageFullName, $setPhotoOrder);
mysqli_stmt_execute($stmt);
move_uploaded_file($fileTempName, $fileDestination);
header("location: photos_edit.php?upload=success");
}
}
}
}else{
echo "Photo is too big!";
exit();
}
}else{
echo "An error ocurred while uploading your image!";
exit();
}
}else{
echo "File type not supported";
exit();
}
}
?>

For example, if you use this code, you can load an image from DB (MySQL) :)
<?php
$connection =mysql_connect("localhost", "root" , "");
$sqlimage = "SELECT * FROM userdetail where `id` = '".$id1."'";
$imageresult1 = mysql_query($sqlimage,$connection);
while($rows = mysql_fetch_assoc($imageresult1))
{
echo'<img height="300" width="300" src="data:image;base64,'.$rows['image'].'">';
}
?>

Related

Why is the following picture weird when trying to upload a picture profile

I have managed to get the picture uploaded into the upload's folder but for some reason, I am getting the following 404 error. From my understanding, it is not recognising the file type and I thought that my code is correct?
I think by doing a profile image, I need two files, one in my header or login page and the other one process the page...
This is the code in one of my files:
<?php
include_once __DIR__.'/header2.php';
include_once __DIR__.'/includes/dbh.php';
$id = $_SESSION['u_id'];
$status = 0;
if (isset($_POST['submit'])) {
$file = $_FILES['file'];
$fileName = $_FILES['file']['name'];
$fileTmpName= $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$fileError = $_FILES['file']['error'];
$fileType = $_FILES['file']['type'];
$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('jpg', 'jpeg', 'png', 'pdf');
if (!in_array($fileActualExt, $allowed)) {
echo "<meta http-equiv='refresh' content='0;url=header2.php?upload_form=error'>";
exit();
} else {
if ($fileError === 1) {
echo "<meta http-equiv='refresh' content='0;url=header2.php?upload_form=error'>";
exit();
} else {
if ($fileSize > 500000) {
echo "<meta http-equiv='refresh' content='0;url=header2.php?upload_form=filesizeerror'>";
exit();
} else {
$fileNameNew = "profile".$id.".".$fileActualExt;
$fileDestination = 'uploads/'.$fileNameNew;
move_uploaded_file($fileTmpName, $fileDestination);
$sql = "UPDATE profileimg
SET status = ?
WHERE userid = ?
;";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)) {
echo "SQL error";
} else {
mysqli_stmt_bind_param($stmt, "ii", $status, $id);
mysqli_stmt_execute($stmt);
echo "<meta http-equiv='refresh' content='0;url=header2.php?upload_form=success'>";
exit();
}
}
}
}
}
And this is the code in my other file:
$sql = "SELECT * FROM users WHERE user_uid = ?;";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo 'SQL error';
exit();
} else {
mysqli_stmt_bind_param($stmt, "s", $_SESSION['u_uid']);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$resultCheck = mysqli_num_rows($result);
if($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$id = $row['user_id'];
$one = 1;
$sqlImg = "SELECT * FROM profileimg WHERE userid = ? limit 1;";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sqlImg)) {
echo 'SQL error';
exit();
} else {
mysqli_stmt_bind_param($stmt, "i", $id);
mysqli_stmt_execute($stmt);
$resultImg = mysqli_stmt_get_result($stmt);
while ($rowImg = mysqli_fetch_assoc($resultImg)) {
if ($rowImg['status'] == 0) {
$filename = "uploads/".$id."*";
$fileinfo = glob($filename);
$fileext = explode(".", $fileinfo[0]);
$fileactualext = $fileext[1];
echo "<img class='profile_picture' src='uploads/profile".$id.".".$fileactualext."?".mt_rand()."'>";
} else {
echo "<img class='default_picture' src='uploads/profiledefault.jpg'>";
}
echo '<div class="welcome">Welcome back '.$row['user_uid'].'!</div>';
}
}
}
}

How to fix Upload image using php and mysqli

I tried replacing mysql to mysqli, but I encountered an error in this code, it worked on mysql before. What is wrong?
Php:
<?php include "../../../_includes/config.php"; ?>
<?php
session_start();
if(!empty($_FILES['userAvatar']['name'])){
$uploadedFile = "";
if(!empty($_FILES["userAvatar"]["type"])){
$filename = $_FILES['userAvatar']['name'];
$valid_extensions = array("jpeg", "jpg", "png");
$temporary = explode(".", $_FILES["userAvatar"]["name"]);
$file_extension = end($temporary);
if((($_FILES["userAvatar"]["type"] == "image/png") || ($_FILES["userAvatar"]["type"] == "image/jpg") || ($_FILES["userAvatar"]["type"] == "image/jpeg")) && in_array($file_extension, $valid_extensions)){
$sourcePath = $_FILES['userAvatar']['tmp_name'];
$targetPath = "../../../uploads/image/".$filename;
if(move_uploaded_file($sourcePath, $targetPath)){
$uploadedFile = $filename;
}
}
}
$display_name = $_POST['display_name'];
$biography = $_POST['biography'];
$sql = mysqli_query($connect, "UPDATE tb_users SET userDisplayName = '$display_name', userBiography = '$biography', userAvatar = '$uploadedFile' WHERE userLogin = '".$_SESSION['is_logged_in']['userLogin']."'") or die(mysqli_error());
if($sql){
echo "ok";
}else{
echo "err";
}
}else{
echo "err";
}
?>
Result always "err".
try this code:-
$sql = mysqli_query($connect, "UPDATE tb_users SET userDisplayName = '$display_name', userBiography = '$biography', userAvatar = '$uploadedFile' WHERE userLogin = '".$_SESSION['is_logged_in']['userLogin']."'") or die(mysqli_error($connect));
// no need of this
if($sql){
echo "ok";
}else{
echo "err";
}
Try this code below
<?php
$dbhost = 'localhost:3306';
$dbuser = 'root';
$dbpass = '';
$dbname = 'your db';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass,$dbname);
if(! $conn ) {
die('Could not connect: ' . mysqli_error());
}
echo 'Connected successfully<br>';
session_start();
if(!empty($_FILES['userAvatar']['name'])){
$uploadedFile = "";
if(!empty($_FILES["userAvatar"]["type"])){
$filename = $_FILES['userAvatar']['name'];
$valid_extensions = array("jpeg", "jpg", "png");
$temporary = explode(".", $_FILES["userAvatar"]["name"]);
$file_extension = end($temporary);
if((($_FILES["userAvatar"]["type"] == "image/png") || ($_FILES["userAvatar"]["type"] == "image/jpg") || ($_FILES["userAvatar"]["type"] == "image/jpeg")) && in_array($file_extension, $valid_extensions)){
$sourcePath = $_FILES['userAvatar']['tmp_name'];
$targetPath = "../../../uploads/image/".$filename;
if(move_uploaded_file($sourcePath, $targetPath)){
$uploadedFile = $filename;
}
}
}
$display_name = $_POST['display_name'];
$biography = $_POST['biography'];
$sql ="UPDATE tb_users SET userDisplayName = '$display_name', userBiography = '$biography', userAvatar = '$uploadedFile' WHERE userLogin = '".$_SESSION['is_logged_in']['userLogin']."'";
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
mysqli_close($conn);
}else{
//echo "err";
}
?>

mysqli_query returns false during file upload in php script

I am new to PHP, I am trying to upload text files to my database. The part, where I am adding the uploaded file to a specified folder works, but I can't add anything to the database. I've found out that the reason for it is that my_sqli_query returns false, but I have no idea, as what is the reason for it. Thanks for help!
<?php
$dbServername = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbName = "project";
$conn = mysqli_connect($dbServername, $dbUsername, $dbPassword, $dbName);
if(isset($_POST['submit'])) {
$file = $_FILES['file'];
$fileName = $_FILES['file']['name'];
$fileTmpName = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$fileError = $_FILES['file']['error'];
$fileType = $_FILES['file']['type'];
$book_title = mysqli_real_escape_string($conn, $_POST['book_title']);
$book_author = mysqli_real_escape_string($conn, $_POST['book_author']);
$book_publisher = mysqli_real_escape_string($conn, $_POST['book_publisher']);
$book_year = mysqli_real_escape_string($conn, $_POST['book_year']);
$book_genre = mysqli_real_escape_string($conn, $_POST['book_genre']);
$fileExt = explode('.', $fileName);
$fileAExt = strtolower(end($fileExt));
$allowedExtensions = array('epub', 'mobi', 'pdf', 'txt');
if (empty($book_title) || empty($book_author) || empty($book_publisher) || empty($book_year) || empty($book_genre)) {
header("Location: ../upload.php?empty");
exit();
}else{
if (in_array($fileAExt, $allowedExtensions)) {
if ($fileError === 0) {
if ($fileSize < 100000) {
$fileNewFilename = uniqid('', true) . $fileName . "." . $fileAExt;
$fileDest = 'uploads/' . $fileNewFilename;
$sql = "INSERT INTO book_db (book_title, book_author, book_publisher, book_year, book_year, file) VALUES ('$book_title', '$book_author', '$book_publisher', '$book_year', '$book_genre', '$file');";
$query = mysqli_query($conn, $sql);
var_dump($query);
move_uploaded_file($fileTmpName, $fileDest);
if ($query != null) {
header("Location: index.php?fail");
} else {
header("Location: index.php?fail");
}
} else {
echo 'fail, too large';
}
} else {
echo 'fail, error';
}
} else {
echo 'fail';
}
}
}

My 'move_uploaded_file()' does not move my image to my specified folder

<?php
include("config.php");
//Get the name of the input type submit
if(ISSET($_POST['sign_up'])) {
$username = trim($_POST['user']);
$password = trim($_POST['pass']);
$gender=$_POST['gen'];
$firstname =($_POST['first']);
$lastname = trim($_POST['last']);
$y=$_POST['y'];
$m=$_POST['m'];
$d=$_POST['d'];
$dob=$y."-".$m."-".$d;
$imgpath=$_FILES['file']['name'];
$imgFile = $_FILES['file']['name'];
$tmp_dir = $_FILES['file']['tmp_name'];
$imgExt = strtolower(pathinfo($imgFile,PATHINFO_EXTENSION));
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif');
$userpic = rand(1000,1000000).".".$imgExt;
if(!empty($username) && !empty($password)) {
$sql = mysql_query("SELECT * FROM users WHERE user_name = '$username'") or die(mysql_error());
if(mysql_num_rows($sql) > 0) {
$msg_error = "Username already registered!";
} else {
if(in_array($imgExt, $valid_extensions)){
mysql_query("INSERT INTO users
values('','$username','".MD5($password)."', '$gender',
'$dob', '$imgpath', 'guest',
'$firstname', '$lastname')")
or die(mysql_error());
$uuid=mysql_query("SELECT * FROM users");
while ($puid=mysql_fetch_array($uuid)){
$pid = $puid['user_id'];
mkdir("userImages/$pid");
move_uploaded_file($_FILES["file"]["tmp_name"], "userImages/$pid/" . $_FILES["file"]["name"]);
}
//image uploaded should be moved to my specified
//folder after the code above is executed
$_SESSION['sname']=$_POST['user'];
$msg_success = "You are now registered!";
}
else{
$msg_error = "Invalid image!";
}
}
}else{
$msg_error = "All fields are required!";
}
}
?>
this is my php code. Can someone help me in figuring out why my 'move_uploaded_file()' is not working?
Check your destination folder permissions. error_get_last could give you some clue to why it doesn't work. Check this example
$targetFile = "userImages/$pid/" . $_FILES["file"]["name"];
if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFile)) {
echo "<P>FILE UPLOADED TO: $target_file</P>";
} else {
echo "<P>MOVE UPLOADED FILE FAILED!</P>";
print_r(error_get_last());
}

PHP upload in database and folder in my root folder

So I'm trying to upload the file name of the image in the database and the image itself will be save in the folder inside a root folder.
In my codes, the image name is able to be saved in the database but the image itself did not save in the folder. Why is that?
Here's my code:
<?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);
$id = $_POST['id'];
header("Location: ../admin/view_all_info.php?id=$id");
}
else {
echo "Image not Uploaded!";
}
}
?>
What seems to be the problem of my codes?
You just get the contain of file. forget to put in target folder use file_put_contents
$target_file = $img_dir . basename($_FILES["image"]["name"]);
$imageName = $_FILES["image"]["name"];
$imageData = file_get_contents($_FILES["image"]["tmp_name"]);
// Write the contents back to the file
file_put_contents($target_file, $imageData);
You can also use move_uploaded_file to uploaded file to a new location
Here try this, I edited your codes.
<?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!";
}
}
?>
just copy and paste it. tell if it worked.
<?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);
$id = $_POST['id'];
//remove
if (file_exists($target_file))
{
$result = unlink($target_file);
if (!$result)
{
//error, display error,
return false;
}
}
//upload
$result = move_uploaded_file($_FILES['image']['tmp_name'], $img_dir);
if(!$result)
{
//error upload
}
header("Location: ../admin/view_all_info.php?id=$id");
}
else {
echo "Image not Uploaded!";
}
}
?>
try

Categories