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

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);
?>

Related

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';
}
}
}

if statement resetting form data variable

If user uploads wrong file then if statement resetting $name to blank. What is the problem in following code?
if(isset($_POST['submit'])){
$conn= new mysqli('localhost','root','','dilip');
if(!$conn){
die("Not connect".mysqli_error);
}
$stm = $conn->prepare("Insert into comment (Name, email, Message, Image) values (?, ?, ?, ?)");
$stm->bind_param('ssss',$name,$email,$message,$image);
$name = $_POST['name'];
$message = $_POST['readerInput'];
$email = $_POST['email'];
$image='upload/comment/default.jpg';
$time = date("s");
//if(isset($_FILES['image'])){
if(is_uploaded_file($_FILES['image']['tmp_name'])){
$tmp_image = $_FILES['image']['size'];
$finfo = new finfo(FILEINFO_MIME_TYPE);
$file = $finfo->file($_FILES['image']['tmp_name']); //This line checks MIME Type of uploaded image
if($file!=='image/jpeg' && $file !=='image/gif' || $tmp_image > 1024*1024*2){ //1024*1024*2 = 2MB
echo "Upload your Profile Image in jpg/gif format and lower than 2mb. Otherwise continue without Image.";
}
else{
$photo = move_uploaded_file($_FILES['image']['tmp_name'],'upload/comment/'.$name.$time.'.jpg');
$image = 'upload/comment/'.$name.$time.'.jpg';
echo '<script> alert("Your file is accepted.")</script>';
$stm->execute();
$message = 'Your Comment';
$name = 'Your Name';
$email = 'Your eMail';
}
}else{
$stm->execute();
$message = 'Your Comment';
$name = 'Your Name';
$email = 'Your eMail';
}
}
Please try with below snippet. You are preparing insert statement before variable initialization and image upload code. I have moved code below file upload code.
if(isset($_POST['submit'])){
$flag = 0;
$conn= new mysqli('localhost','root','','dilip');
if(!$conn){
die("Not connect".mysqli_error);
}
$name = $_POST['name'];
$message = $_POST['readerInput'];
$email = $_POST['email'];
$image='upload/comment/default.jpg';
$time = date("s");
//if(isset($_FILES['image'])){
if(is_uploaded_file($_FILES['image']['tmp_name'])){
$tmp_image = $_FILES['image']['size'];
$finfo = new finfo(FILEINFO_MIME_TYPE);
$file = $finfo->file($_FILES['image']['tmp_name']); //This line checks MIME Type of uploaded image
if($file!=='image/jpeg' && $file !=='image/gif' || $tmp_image > 1024*1024*2){ //1024*1024*2 = 2MB
echo "Upload your Profile Image in jpg/gif format and lower than 2mb. Otherwise continue without Image.";
$flag = 1;
}else{
$photo = move_uploaded_file($_FILES['image']['tmp_name'],'upload/comment/'.$name.$time.'.jpg');
$image = 'upload/comment/'.$name.$time.'.jpg';
echo '<script> alert("Your file is accepted.")</script>';
}
}
$stm = $conn->prepare("Insert into comment (Name, email, Message, Image) values (?, ?, ?, ?)");
$stm->bind_param($name,$email,$message,$image);
if($flag==0){
$stm->execute();
}
}

alternate to upload image or not

I am new in stackoverflow and in PHP too, so I want to describe my problem first. Sorry if I have bad grammar, I am not native though.
I make a form that let user post (to database) with or without an image, this the code
$link = mysqli_connect('localhost', 'root', '12345!##', 'pklapps') or die("Couldnt connect to the server");
//public info dari admin
if (isset($_POST["title"]) && isset($_POST["content"]) && isset($_POST["category"])) {
$title = $_POST['title'];
$desc = $_POST['content'];
$lat = $_POST['latitude'];
$long = $_POST['longitude'];
$category = $_POST['category'];
$image = $_POST['userfile'];
if (!isset($_FILES['userfile'])) {
$query = "INSERT INTO public_info (title, content, category) VALUES ('$title','$desc','$category')";
$result = mysqli_query($link, $query);
if ($result) {
header('Location: post.php?success');
} else {
header('Location: post.php?error');
}
} else {
$fileName = $_FILES['userfile']['name'];
$target = "uploads/";
$fileTarget = $target.$fileName;
$tempFileName = $_FILES["userfile"]["tmp_name"];
$result = move_uploaded_file($tempFileName,$fileTarget);
/*
* If file was successfully uploaded in the destination folder
*/
if ($result) {
header('Location: post.php?success');
$query = "INSERT INTO public_info (title, content, category, imagePath) VALUES ('$title','$desc','$category', '$fileTarget')";
$link->query($query) or die("Error : ".mysqli_error($link));
} else {
header('Location: post.php?errimg');
}
mysqli_close($link);
}
}
and the form goes normal when i attach the image or file but it goes to header('Location: post.php?errimg'); when i not attach the image. Please help me with this, thank you.
Replace your if condition from !isset($_FILES['userfile']) to empty($_FILES['userfile']['name'])
//if (!isset($_POST[]))
$title = $_POST['title'];
$desc = $_POST['content'];
$lat = $_POST['latitude'];
$long = $_POST['longitude'];
$category = $_POST['category'];
$image = $_POST['userfile'];
if(empty($_FILES['userfile']['name'])) {
$query = "INSERT INTO public_info (title, content, category) VALUES ('$title','$desc','$category')";
$result = mysqli_query($link, $query);
if ($result) {
header('Location: post.php?success');
}
else {
header('Location: post.php?error');
}
}
else {
$fileName = $_FILES['userfile']['name'];
$target = "uploads/";
$fileTarget = $target.$fileName;
$tempFileName = $_FILES["userfile"]["tmp_name"];
$result = move_uploaded_file($tempFileName,$fileTarget);
/*
* If file was successfully uploaded in the destination folder
*/
if($result) {
header('Location: post.php?success');
$query = "INSERT INTO public_info (title, content, category, imagePath) VALUES ('$title','$desc','$category', '$fileTarget')";
$link->query($query) or die("Error : ".mysqli_error($link));
}
else {
header('Location: post.php?errimg');
}
mysqli_close($link);
}
// $query = "INSERT INTO public_info (title, content, category) VALUES ('$title','$desc','$category')";
} ?>

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

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

Categories