How to fix Upload image using php and mysqli - php

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";
}
?>

Related

Displaying images from Database not working

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'].'">';
}
?>

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());
}

Uploading image and form to database

So, i've been wondering for this script and still can't get it right. For some reason it won't save to my database. Any ideas why it's not working? Would appreciate any help. Thanks! Here's my script.
<?php
include_once ("database.php"); ?>
<?php
if (isset($_POST['anisave'])) {
$id = $_POST['id'];
$title = $_POST['title'];
$genre = $_POST['genre'];
$description = $_POST['description'];
$start = $_POST['start'];
$stop = $_POST['stop'];
$image_file = $_FILES['image']['name'];
$type = $_FILES['image']['type'];
$size = $_FILES['image']['size'];
if (empty($image_file) || empty($id)) {
echo "Sorry, form is not complete yet!";
header('Location: add.php');
}
else{
$query_id = mysql_query("SELECT * FROM anidata WHERE id = '$id'");
$check = mysql_num_rows($query_id);
if ($check > 0) {
echo "Sorry, Anime ID not available";
header('Location: add.php');
}
else{
if ($type != "image/gif" && $type != "image/jpg" && $type != "image/jpeg" && $type != "image/png") {
echo "Invalid image file, please use JPEG,JPG,PNG or GIF to upload the image."
header('Location: add.php');
}
if ($size > 10000) {
echo "Affordable file is under 10mB."
header('Location: add.php');
}
else{
$upload_directory = 'upload/';
$temp = $upload_directory.$image_file;
if (move_uploaded_file($_FILES['image']['tmp_name'] , $temp)) {
$sql = "INSERT INTO anidata VALUES ('$id', '$title', '$temp', '$genre', '$description','$start', '$stop')";
$query = mysql_query($sql)
if ($query) {
header('Location: view.php');
}
else{
echo mysql_query();
}
}
else{
echo "<p> Upload Failed, error code = " . $_FILES['location']['error']. "</p>";
}
}
}
}
}
else{
unset($_POST['anisave']);
}
?>

move file name with unique id from new folder to SQL database

I've looked around and haven't found particularly what I'm after.
I have quite a few forms with text input and file uploads.
I've figured how to upload a file, give it a unique ID and get it into my web server folder. Pretty smooth sailing. However, I would like to also get that fancy new ID into my MySQL database.
I've separated my upload.php page with text forms going to the database
<?php
//Connecting and Sending data to the database follows
$dbc = mysqli_connect('localhost', 'root', 'root', 'surfboardhub')
or die('Error connecting to MySQL server');
//Get values from
$location = "";
$price = "";
$thick = "";
$width = "";
$height ="";
$model = "";
$brand = "";
$email = "";
$category = "";
if(isset($_POST['location'])){ $location = $_POST['location']; }
if(isset($_POST['price'])){ $price = $_POST['price']; }
if(isset($_POST['thick'])){ $thick = $_POST['thick']; }
if(isset($_POST['width'])){ $width = $_POST['width']; }
if(isset($_POST['height'])){ $height = $_POST['height']; }
if(isset($_POST['model'])){ $model = $_POST['model']; }
if(isset($_POST['brand'])){ $brand = $_POST['brand']; }
if(isset($_POST['email'])){ $email = $_POST['email']; }
//if(isset($_POST['image'])){ $imagename = $_POST['imagename']; }
//if(isset($_POST['mime'])){ $mime = $_POST['mime']; }
$query = "INSERT INTO uploads (location, price, thick, width, height, model, brand, email,category)
VALUES ('$location', '$price','$thick','$width','$height', '$model', '$brand', '$email','$category')";
$result = mysqli_query($dbc,$query)
or die('Error querying database.');
mysqli_close($dbc);
and then my bit to get the file to its new location in my web server.
$name = $_FILES['image']['name'];
$extension = strtolower(substr($name, strpos($name, '.') + 1));
$type = $_FILES['image']['type'];
$tmp_name = $_FILES['image']['tmp_name'];
if (isset($name)) {
if (!empty($name)) {
if (($extension=='jpg'||$extension=='jpeg'||$extension=='png'||$extension=="gif")&&$type=='image/jpeg'||$type=='image/png'||$type=='image/gif') {
$location = 'uploads/';
$location = $location . uniqid();
if (move_uploaded_file($tmp_name, $location.$name)) {
echo 'uploaded!';
}
else {
echo 'There was an error.';
}
} else {
echo 'File must be jpg/jpeg, png, or gif.';
}
} else {
echo 'Please choose a file';
}
}
?>
Basically, I need to get that new unique ID to go to where the text information is going, because they're all being submitted at once. And I'd like to be able to figure out who uploaded what if need be. If it didn't have a unique ID I can get it to work, but for some reason having that uniqid trips me up. Thoughts? Much obliged.
Save the uniqid() to a PHP variable and then you can use it in more than one place:
First, create an ID:
<?php
$ID = uniqid();
?>
Then, save your file, using your new $ID variable:
<?php
$name = $_FILES['image']['name'];
$extension = strtolower(substr($name, strpos($name, '.') + 1));
$type = $_FILES['image']['type'];
$tmp_name = $_FILES['image']['tmp_name'];
if (isset($name)) {
if (!empty($name)) {
if (($extension=='jpg'||$extension=='jpeg'||$extension=='png'||$extension=="gif")&&$type=='image/jpeg'||$type=='image/png'||$type=='image/gif') {
$location = 'uploads/';
$location = $location . $ID;
if (move_uploaded_file($tmp_name, $location.$name)) {
echo 'uploaded!';
} else {
echo 'There was an error.';
}
} else {
echo 'File must be jpg/jpeg, png, or gif.';
}
} else {
echo 'Please choose a file';
}
}
?>
Then, save your data to the db, including $ID
<?php
//Connecting and Sending data to the database follows
$dbc = mysqli_connect('localhost', 'root', 'root', 'surfboardhub')
or die('Error connecting to MySQL server');
//Get values from
$location = "";
$price = "";
$thick = "";
$width = "";
$height ="";
$model = "";
$brand = "";
$email = "";
$category = "";
if(isset($_POST['location'])){ $location = $_POST['location']; }
if(isset($_POST['price'])){ $price = $_POST['price']; }
if(isset($_POST['thick'])){ $thick = $_POST['thick']; }
if(isset($_POST['width'])){ $width = $_POST['width']; }
if(isset($_POST['height'])){ $height = $_POST['height']; }
if(isset($_POST['model'])){ $model = $_POST['model']; }
if(isset($_POST['brand'])){ $brand = $_POST['brand']; }
if(isset($_POST['email'])){ $email = $_POST['email']; }
//if(isset($_POST['image'])){ $imagename = $_POST['imagename']; }
//if(isset($_POST['mime'])){ $mime = $_POST['mime']; }
$query = "INSERT INTO uploads (ID, location, price, thick, width, height, model, brand, email,category)
VALUES ('$ID', '$location', '$price','$thick','$width','$height', '$model', '$brand', '$email','$category')";
$result = mysqli_query($dbc,$query)
or die('Error querying database.');
mysqli_close($dbc);
?>

Categories