Php is uploading images but not inserting in database - php

I'm developing a back end for my blog but the code to upload images isn't working as expected.
When i submit it uploads the image and moves it to the designated folder but in the database there is no record inserted. Here is the php for uploading
<?php
session_start();
include('Connections/conn.php');
if (!isset($_SESSION['userid'])) {
header("location:index.php");
}
$suc=" ";
$writer=$_SESSION['my_username'];
if(isset($_POST['submit']))
{
error_reporting(E_ALL ^ E_NOTICE);
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
$title=$_POST['title'];
$intro=$_POST['intro'];
$body=$_POST['body'];
$keywords=$_POST['keywords'];
$date=$_POST['date'];
$fileToUpload=$_POST['fileToUpload'];
$sql2="Insert into articles(title,intro,body,keywords,date,writer,fileToUpload)VALUES('$title','$intro','$body','$keywords','$date','$writer','$target_file')"or die(mysqli_error());
$result2 = mysqli_query($db_conn, $sql2);
$suc=" <div class='alert alert-success'>
<span><b>Success</b>: New article posted successfully!</span>
</div>";
}
?>
And here is the form
<form method="POST" action"<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data">
<div class="form-group">
<label>Title</label>
<input type="text" id="title" name="title" class="form-control" required/>
</div>
<div class="form-group">
<label>Intro</label>
<textarea id="intro" name="intro" class="form-control" required></textarea>
</div>
<div class="form-group">
<label>Enter keyword tags</label><br/>
<div>
<input type="text" id="keywords" name="keywords" class="tagsinput" required/>
</div>
</div>
<div class="form-group">
<label>Date</label><br/>
<div>
<div class="input-group">
<span class="input-group-addon"><span class="fa fa-calendar"></span></span>
<input type="text" id="date" name="date" class="form-control datepicker" placeholder="Select Date" required>
</div>
<span class="help-block">Click on input field to select date</span>
</div>
<div class="form-group">
<div>
<label>Picture</label>
<input type="file" multiple class="file" data-preview-file-type="any" name="fileToUpload" id="fileToUpload"/>
</div>
</div>
<div>
<div class="block">
<p>Type the content below, note that you can extend the height of the editor by dragging the bottom border.</p>
<textarea class="summernote" id="body" name="body" placeholder="Enter the body text" required>
</textarea>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-6">
<button class="btn btn-danger btn-block" type="reset">Reset</button>
</div>
<div class="col-md-6">
<button class="btn btn-info btn-block" type="submit" name="submit" value="submit">Publish Article</button>
</div>
</div>
</form>

Replace
$fileToUpload=$_POST['fileToUpload'];
with
$fileToUpload=$_FILES['fileToUpload']['name'];

Try this
$sql2="INSERT INTO articles(title,intro,body,keywords,date,writer,fileToUpload)VALUES('$title','$intro','$body','$keywords','$date','$writer','$target_file')");
if (!mysqli_query($db_conn, sql2))
{
echo("Error description: " . mysqli_error($db_conn));
}
else{
echo "Inserted";
}
and my opinion is add the insert code after move_uploaded_file get success

Related

Upload file Warning: move_uploaded_file(../view/pictureswhy.PNG): failed to open stream: Permission denied

Have been trying to upload an image and it is not working as expected. The error in the title is being displayed on the form. The image is being inserted via a file in the 'View' and checked in the 'Controller', however, when it comes to the final upload it fails, due to permissions I assume...
I have given both files in the view and controller the correct permissions for uploading files - in FileZilla.
The code is:
FORM - View
<form class="article" id="article-form" name="article" method="post" enctype="multipart/form-data">
<ol>
<li>
<label for="heading">Heading</label> <span id="headingMessage"></span>
<input name="heading" id="heading" class="form-control" type="text" required>
</li>
<li>
<label for="topic">Topic</label> <span id="topicMessage" required></span>
<input name="topic" id="topic" class="form-control" type="text" list="football">
<datalist id="football">
<option value="Scotland"></option>
<option value="England"></option>
<option value="Spain"></option>
</datalist>
</li>
<li>
<label for="summary">Summary</label> <span id="summaryMessage"></span>
<input name="summary" id="summary" class="form-control" type="text">
</li>
<li>
<label for="thumbnail">Thumbnail Link</label> <span id="thumbnailMessage"></span>
<!-- <input name="thumbnail" id="thumbnail" class="form-control" type="text" required> -->
<input type="file" name="file" id="file">
</li>
<li>
<label for="video">Video</label> <span id="videoMessage"></span>
<input name="video" id="video" class="form-control" type="text">
</li>
<li>
<label for="articleText">Text</label>
<textarea name="articleText" id="articleText" class="md-textarea form-control" required></textarea>
</li>
<!-- <li>
<div class="g-recaptcha" data-sitekey="6LcUAnQUAAAAAPeF1u6Hcnf0Y5TfS4-0xitZ7ZeZ"></div>
</li> -->
</ol>
<input class="btn btn-success" id="formButton" type="submit" name="submit"value="Submit" name="submit">
<input class="btn btn-danger" id="formButton" type="reset" value="Reset">
</form>
The controller -
//check image
$target_dir = "../view/pictures";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
$uploadOk = 0;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["file"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 2;
//$thumbnail = '<img class="img-responsive" id="articleImage" src="'.$_POST["file"].'">';
echo $target_file;
} else {
echo "File is not an image. <hr>";
$uploadOk = 0;
}
}
$thumbnail=$target_file;
include("../model/api-article.php") ;
if($uploadOk>1)
{
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.";
$articleTxt = insertArticle($headline, $topic, $summary, $text, $thumbnail,$video,$date,$userId);
} else {
echo "Sorry, there was an error uploading your file.";
}
}else{
echo "Article not inserted - only upload images (PNG, JPEG)";
}
}
Please excuse the indenting
It's may not enough to give permission to the upload file - you need to permit the whole folder where you are uploading your images.

PHP Not Posting Data After Submit

I cannot figure out why my form does not want to submit its data into my recipes table after clicking submit. When I click the submit button the form just refreshes,
I have an echo for successful set but it does not appear along with no error messages and no data in my database.
Here is the HTML
<div class="row">
<div class="main-login main-center">
<h1>Add Recipe</h1>
<form enctype="multipart/form-data" action="#" method="post">
<div class="form-group">
<label for="recipe_name" class="cols-sm-2 control-label">Recipe Name</label>
<div class="cols-sm-10">
<div class="input-group">
<input type="text" class="form-control" name="recipe_name" id="recipe_name" placeholder="Recipe Name"/>
</div>
</div>
</div>
<div class="form-group">
<label for="recipe_duration" class="cols-sm-2 control-label"> Recipe Duration </label>
<div class="cols-sm-10">
<div class="input-group">
<input type="text" class="form-control" name="recipe_duration" id="recipe_duration" placeholder="Recipe Duration"/>
</div>
</div>
</div>
<div class="form-group">
<label for="recipe_ingredient" class="cols-sm-2 control-label"> Ingredients </label>
<div class="cols-sm-10">
<div class="input-group">
<input type="text" class="form-control" name="recipe_ingredient" id="recipe_ingredient" placeholder="Ingredients"/>
</div>
</div>
</div>
<div class="form-group">
<label for="recipe_nutrition" class="cols-sm-2 control-label"> Recipe Nutrition </label>
<div class="cols-sm-10">
<div class="input-group">
<input type="text" class="form-control" name="recipe_nutrition" id="recipe_nutrition" placeholder="Recipe Nutrition"/>
</div>
</div>
</div>
<div class="form-group">
<label for="recipe_method" class="cols-sm-2 control-label"> Recipe Directions </label>
<div class="cols-sm-10">
<div class="input-group">
<input type="text" class="form-control" name="recipe_method" id="recipe_method" placeholder="Recipe Directions"/>
</div>
</div>
</div>
<div class="form-group">
<label for="profile_image">Recipe Image</label>
<input type="file" name="recipe_image" id="recipe_image">
<p class="help-block">Upload an image of the recipe</p>
<img class="recipeImage" src="./recipe_images/"/>
</div>
<div class="form-group">
<button type="submit" class="btn btn-success btn-lg btn-block login-button">Submit</button>
</div>
</form>
</div>
and PHP
<?php
if(isset($_POST['submit'])){
//Insert DB
$query = "INSERT INTO recipes (recipe_name, recipe_duration, recipe_ingredient, recipe_nutrition, recipe_method) VALUES (:recipe_name, :recipe_duration, :recipe_in
gredient, :recipe_nutrition, :recipe_method)";
$result = $DBH->prepare($query);
$result->bindParam(':recipe_name', $_POST['recipe_name']);
$result->bindParam(':recipe_duration', $_POST['recipe_duration']);
$result->bindParam(':recipe_ingredient', $_POST['recipe_ingredient']);
$result->bindParam(':recipe_nutrition', $_POST['recipe_nutrition']);
$result->bindParam(':recipe_method', $_POST['recipe_method']);
if($target_file){
$result->bindParam(':recipeImage', $newFilename);
}
if($result->execute()){
echo '<div class="alert alert-success" role="alert">Recipe Added!</div>';
}
if($_FILES['recipeImage']["name"]){
//Let's add a random string of numbers to the start of the filename to make it unique!
$newFilename = md5(uniqid(rand(), true)).$_FILES["profile_image"]["name"];
$target_file = "./recipe_images/" . basename($newFilename);
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
$check = getimagesize($_FILES["recipeImage"]["tmp_name"]);
if($check === false) {
echo "File is not an image!";
$uploadError = true;
}
//Check file already exists - It really, really shouldn't!
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadError = true;
}
// Check file size
if ($_FILES["recipeImage"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadError = true;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadError = true;
}
// Did we hit an error?
if ($uploadError) {
echo "Sorry, your file was not uploaded.";
} else {
//Save file
if (move_uploaded_file($_FILES["recipeImage"]["tmp_name"], $target_file)) {
//Success!
} else {
echo "Sorry, there was an error uploading your file.";
}
}
}
}
?>
Because you have no element with name="submit" and you're testing for it here if(isset($_POST['submit'])){
Your submit should be an input, not a button:
<input type="submit" class="btn btn-success btn-lg btn-block login-button" value="Submit" />
<input type="submit" name="submit" value="Submit"class="btn btn-success btn-lg btn-block login-button">
change the submit button like this
<button type="submit" class="btn btn-success btn-lg btn-block login-button">Submit</button>
instead of
<input type="submit" class="btn btn-success btn-lg btn-block login-button" value="Submit" name="submit">
Change
<button type="submit" class="btn btn-success btn-lg btn-block login-button">Submit</button>
To
<button type="submit" name="submit" class="btn btn-success btn-lg btn-block login-button">Submit</button>
Actually you needed to add a name attribute to the button element, so that you can identify the element in the following php line
if(isset($_POST['submit'])){
The line above checks for a "POST"ed element identified by the name 'submit'.

How to upload multiple images into PHP and Mysql

Hello everyone,
I have a table consist of 10 columns which in 4 of them i want to insert the image paths.
can any one guide me how to insert the image paths into database along with other 6 more columns data in a single query and upload the images into server(inside a folder).
here my html code:
<div class="panel-body">
<div class="form-group">
<label style="align-content:center" for="inputdefault">Product full name</label>
<input class="form-control" id="inputdefault" name="name2" type="text">
</div>
<div class="panel-body">
<div class="form-group">
<label style="align-content:center" for="inputdefault">Product category</label>
<input class="form-control" id="inputdefault2" name="name1" type="text">
</div>
<div class="panel-body">
<div class="form-group">
<label style="align-content:center" for="inputdefault">Product qty</label>
<input class="form-control" id="inputdefault3" name="name3" type="text">
</div>
<div class="panel-body">
<div class="form-group">
<label style="align-content:center" for="inputdefault">Picture 1.</label>
<input type="file" id="file3" name="files[]" multiple="multiple" accept="image/*" />
</div>
<div class="form-group">
<label style="align-content:center" for="inputdefault">Picture 2.</label>
<input type="file" id="file3" name="files[]" multiple="multiple" accept="image/*" />
</div>
<div class="form-group">
<label style="align-content:center" for="inputdefault">Picture 3.</label>
<input type="file" id="file3" name="files[]" multiple="multiple" accept="image/*" />
</div>
<div class="form-group">
<label style="align-content:center" for="inputdefault">Picture 4.</label>
<input type="file" id="file3" name="files[]" multiple="multiple" accept="image/*" />
</div>
Here php code :
Note: I did not get image file names in any variable to added into query, everything is working fine here just need to work with images upload and store the path in to database
<?php
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$pname= stripslashes($_REQUEST['name1']);
$pcat= stripslashes($_REQUEST['name2']);
$pprice= stripslashes($_REQUEST['name3']);
$pqty= stripslashes($_REQUEST['qty']);
$pdesc=stripslashes($_REQUEST['description']);
//$spassword=stripslashes($_REQUEST['img']);
$sqlinsert ="INSERT INTO `noorizone`.`products` VALUES ('$pname', '$pcat', '$pprice')";
if($con-> query($sqlinsert)=== true)
{
echo "<center><b style='color:green;'> added successfully... </b>";
echo"</center>";
}
else{
echo "<b style='color:red;'> cant register". $con->error."</b>";
}
}
?>
THANKS IN ADVANCE !!!
This is example for me, you can learn my codes :
$fileImageStatus = ""; // Create your variable for files
if(isset($_FILES['files_status']['name'])){ // Checking value for all input
$fileImageName = array(); // Make an array
for($i = 0; $i < count($_FILES['files_status']['name']); $i++){ // Looping
$imageName = $_FILES['files_status']['name'][$i]; // Give a variable with index from array looped
$uploadPath = '././sistem/users/members/'.$idPenerima.'/unggahan/';
move_uploaded_file($imageTmp, $uploadPath.$imageName); // Path upload
$fileImageName[] = $imageName; // Setting a values from array
}
$fileImageStatus = implode(",", $fileImageName); // Make that values an string
}
// in here you can insert to database with value from $fileImageStatus
I think if you change the name of the file to say file1 instead of file[], you will be fine.
See an example from W3Schools.com
<!DOCTYPE html>
<html>
<body>
<!--
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
?>
-->
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
Here is a Good tutorial on how to upload multiple images into PHP and Mysql
http://www.wdb24.com/how-to-upload-multiple-images-in-php-and-store-in-mysql/

Upload more than one image to a server folder

I have a form through which a user can upload images to a server folder, and the path gets saved in the database.
Currently the code that I have works fine when the user has to input only one image; however, I want to do something like the following with the form, so that user can upload more than one image:
<form class="form-horizontal" role="form" action="insertimage.php?id=<?php echo $_GET['id']; ?>" enctype="multipart/form-data" method="post">
<div class="col-md-6">
<div class="form-group">
<label class="col-lg-4 control-label">Select Image 1</label>
<div class="col-lg-6">
<input type="file" name="file" id="fileToUpload">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="col-lg-4 control-label">Select Image 2</label>
<div class="col-lg-6">
<input type="file" name="file1" id="fileToUpload">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="col-lg-4 control-label">Select Image 3</label>
<div class="col-lg-6">
<input type="file" name="file2" id="fileToUpload">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="col-md-3 control-label"></label>
<div class="col-md-8">
<input class="btn btn-primary" value="Save Changes" type="submit" name="submit">
</div>
</div>
</div>
</form>
The PHP code at back end for uploading one image is insertimage.php:
<?php
$file_exts = array("jpg", "bmp", "jpeg", "gif", "png");
$upload_exts = end(explode(".", $_FILES["file"]["name"]));
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/png")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 2000000)
&& in_array($upload_exts, $file_exts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
// Enter your path to upload file here
if (file_exists("uploads/" .$_FILES["file"]["name"]))
{
echo "<div class='error'>"."(".$_FILES["file"]["name"].")"." already exists. "."</div>";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],"uploads/" . $_FILES["file"]["name"]);
echo "<div class='sucess'>"."Stored in: " . "uploads/" . $_FILES["file"]["name"]."</div>";
` }
}
}
else
{
echo "<div class='error'>Invalid file</div>";
}
?>
Can anyone please tell me how I can support uploading 3 images with help of the above code?
With this you are able to select multiple image with use of ctrl
<input type="file" name="file[]" id="fileToUpload" multiple />
On Server side use loop
for ($1=0;i<count($dataFile);$i++){
//your upload code ;
$_FILES["file"]["name"][$i];//go for each and every i position for all
}
You can use file array for multiple images at a time with multiple attribute in the html line like:
<input type="file" name="file[]" id="fileToUpload" multiple />
This will give you the array of files which you can debug by
print_r($_FILES);
And you also have to change the code that saves the data as there is error that it can only have one file at a time try for loop my debugging with
$_FILES

Image Uploading using bootstrap

I have created an image uploader using the file upload option in Bootstrap. I want to upload images to a separate folder and keep the path name in the database. When I click the upload button the code does not show any error message but it doesn't works. Could you please help me to solve this problem? I have attached my code here:
image_upload_form_ui.php
<form id="fileupload" class="form-horizontal" method="POST" action="phpscripts/test.php" enctype="multipart/form-data">
<div class="control-group "> <!-- start of image -->
<label class="control-label">Avatar</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="icon-camera"></i></span>
<!-- file upload-->
<div class="fileupload fileupload-new" data-provides="fileupload">
<div class="fileupload-preview thumbnail" style="width: 200px; height: 150px;"><img src="http://www.placehold.it/200x150/EFEFEF/AAAAAA&text=no+image"/></div>
<div>
<span class="btn btn-file"><span class="fileupload-new">Select image</span>
<span class="fileupload-exists">Change</span>
<input type="hidden" name="MAX_FILE_SIZE" value="204800" />
<input type="file" name="image" /></span>
Remove
</div>
</div>
<!--end of file upload -->
</div>
</div>
</div><!-- end of image -->
<div class="control-group"> <!-- start of buttons -->
<label class="control-label"></label>
<div class="controls">
<button type="submit" class="btn btn-primary" >Upload</button>
</div>
</div> <!-- end of buttons -->
</form>
here is my test.php
<?php
include "dbConnect.php";
//connect to the database
dbConnect();
$path = "uploads/";
$valid_formats = array("jpg","jpeg", "png", "gif", "bmp");
if(isset($_POST['image']))
{echo "1";
$name = $_FILES['image']['name'];
$size = $_FILES['image']['size'];
if(strlen($name))
{
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats))
{
if($size<(2048*2048))
{
$actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
$tmp = $_FILES['image']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
mysql_query("UPDATE tutor SET avatar='$actual_image_name' WHERE userName='Isuru'");
echo "Hari";
}else
echo die(mysql_error());
}else
echo "exceed the file size";
}else
echo "Not a valid format";
}else
echo "no file is selected";
}
?>
Your code in test.php is checking the $_POST variable to see if a file was submitted via the form, but you probably want to be checking $_FILES. Check out the PHP documentation on file uploads for more information.
Try changing:
if(isset($_POST['image']))
to
if(isset($_FILES['image']))

Categories