Image upload php mysql - php

I am trying to upload 2 images and save the file name for each file to MySQL database. I have tried different options but I can't get this to work.
On my MYSQL table field name for file name is called file_name
varchar 500
I can save the other form data into my database without a problem.
However I can't get the image(s) uploaded.
Following is my image portion of the web form.
Here is the FORM action area
<form method="post" action="php/smartprocess.php" enctype="multipart/form-data" id="smart-form">
My image upload section as following
smartprocess.php section is
<?php
if (!isset($_SESSION)) session_start();
if(!$_POST) exit;
require 'database.php';
include dirname(__FILE__).'/settings/settings.php';
include dirname(__FILE__).'/functions/emailValidation.php';
$TechName = strip_tags(trim($_POST["TechName"]));
$FullAssembly = strip_tags(trim($_POST["FullAssembly"]));
$Notes = strip_tags(trim($_POST["Notes"]));
$SignedDate = strip_tags(trim($_POST["SignedDate"]));
$captcha = strip_tags(trim($_POST["captcha"]));
try {
$q = "INSERT INTO tportal (TechName, FullAssembly, Notes, SignedDate)
VALUES (:TechName, :FullAssembly, :Notes, :SignedDate)";
$query = $conn -> prepare($q);
$results = $query -> execute(array(
":TechName" => $TechName,
":FullAssembly" => $FullAssembly,
":Notes" => $Notes,
":SignedDate" => $SignedDate,
));
if ($conn->query($q)) {
$errors = array();
echo '<div class="alert notification alert-success">Problem has accured please try again.</div>';
//Javascript alert top
/*echo "<script type= 'text/javascript'>alert('Issue adding data');</script>";*/
}
else{
echo '<div class="alert notification alert-success">Your message has been sent successfully!</div>';
//Javascript alert top
/*echo "<script type= 'text/javascript'>alert('Data not successfully Inserted. $PocketCond');</script>";*/
}
$conn = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
<?php
if(isset($_POST["captcha"])){
if (!$captcha) {
$errors[] = "You must enter the captcha code";
} else if (($captcha) != $_SESSION['gfm_captcha']) {
$errors[] = "Captcha code is incorrect";
}
}
?>
<div class="section">
<label for="file1" class="field-label">
Upload another image - <span class="small-text fine-grey"> (ONLY JPG : PNG : PDF) </span>
</label>
<label class="field prepend-icon file">
<span class="button btn-primary"> Choose File </span>
<input type="file" class="gui-file" name="image" id="file1"
onChange="document.getElementById('uploader1').value = this.value;">
<input type="text" class="gui-input" id="uploader1" placeholder="no file selected" readonly>
<span class="field-icon"><i class="fa fa-upload"></i></span>
</label>
</div><!-- end section -->
Your help and time is much appreciated.
Sincerely,

Use $_FILES variable of php to help your files uploaded. There is a simple tutorial on file upload in php here

Related

how to prevent data empty in db when no file upload on editing that file in php

Let me explain my problem briefly.I have image names in MYSQL database.
I need to change the image name when user uploads a new image using file input field.Otherwise the image name in database remain same.But My problem is when user doesn't upload any images the image name becomes empty in database.
My HTML code for changing a image
<form method="post" action="edit_store_img.php?id=<?php echo (int)$store['id'] ?>" class="clearfix" enctype="multipart/form-data">
<div class="form-group">
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">
<i class="glyphicon glyphicon-th-large"></i>
</span>
<label for="file">Upload a store image</label>
<input type="file" name="storepic" value="<?php echo $store['pic']; ?>"/>
</div>
</div>
<hr>
<br>
<h3>Change Map Image For Store <?php echo remove_junk($store['name']);?></h3>
<hr>
<!-- below code is for map image -->
<?php if($store['pic'] === '0'): ?>
<img class="img-avatar img-circle" src="uploads/mapimg/no_image.jpg" alt="Store_map_picture" style="width: 200px;height: 200px;">
<?php else: ?>
<img class="img-avatar img-circle" src="uploads/mapimg/<?php echo $store['map']; ?>" alt="Store_map_picture" style="width: 200px;height: 200px;">
<?php endif;
?>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">
<i class="glyphicon glyphicon-th-large"></i>
</span>
<label for="file">Upload a Store map location image</label>
<input type="file" name="mappic" value="<?php echo $store['map']; ?>"/>
</div>
</div>
<div class="col-md-12">
<button type="submit" name="edit_store_img" class="add-btn">Update Store image</button>
</div>
</form>
This is my PHP file for getting ID for that particular image
<?php
$store = find_by_id('store',(int)$_GET['id']);
if(!$store)
{
$session->msg("d","Missing store id.");
redirect('store.php');
}
?>
This is my PHP code for Storing image name in database
<?php
if(isset($_POST['edit_store_img']))
{
if(empty($errors))
{
/*below queries is for image upload */
$msg = "";
$map = $_FILES["mappic"]["name"];
$tempname = $_FILES["mappic"]["tmp_name"];
$mapfolder = "uploads/mapimg/".$map;
// Now let's move the uploaded image into the mapfolder: image
if (move_uploaded_file($tempname, $mapfolder)) {
$msg = "map Image uploaded successfully";
}else{
$msg = "Failed to upload image";
}
$message = "";
$pic = $_FILES["storepic"]["name"];
$tempname = $_FILES["storepic"]["tmp_name"];
$picfolder = "uploads/storeimg/".$pic;
// Now let's move the uploaded image into the folder image
if (move_uploaded_file($tempname, $picfolder)) {
$message = "Image uploaded successfully";
}else{
$message = "Failed to upload image";
}
$query = "UPDATE store SET";
$query .=" map ='{$map}', pic ='{$pic}'";
$query .=" WHERE id ='{$store['id']}'";
$result = $db->query($query);
if($result && $db->affected_rows() === 1){
$session->msg('s',"store updated ");
redirect('store.php', false);
} else {
$session->msg('d',' Sorry failed to updated!');
redirect('edit_store_img.php?id='.$store['id'], false);
}
}
else
{
$session->msg("d", $errors);
redirect('edit_store_img.php?id='.$store['id'], false);
}
}
?>
I Need to store image name when user doesn't upload image.I need to avoid the image name db field becomes empty.
Below quirky will somehow fix your problem; however, this is not the correct way I think;
$query .=" map = IF('{$map}' != '', '{$map}', map), pic = IF('{$pic}' != '', '{$pic}', pic)";
We are just asking the database to update with the exiting column value if the passed value is empty.
The correct way should be not to take it for granted that the user have uploaded a file; as you are doing with these below lines in your code;
$map = $_FILES["mappic"]["name"];
...
$pic = $_FILES["storepic"]["name"];
You should be actually using IF conditions to check if some viable value has been set for those _FILES variables so you know what to process for and what not, and prepare your SQL UPDATE statement accordingly.

Adding data to mySQL using PHP

I feel this should be straight forward but the data isnt going in to the table.
When I try to save the data the code executes and displays this message:
$statusMsg1 = "A problem occurred, please try again.";
Which leads me to think the problem must be with the SQL, but nothing is standing out to me to highlight what the issue is.
I changed the SQL so that insert raw text, but this produces the same message.
postCodes.php
<?php
// Form saubmission script
include_once 'submit.php';
/* Attempt MySQL server connection. */
$mysqli = new mysqli("127.0.0.1", "root", "root", "bookingpage");
// Check connection
if($mysqli === false){
die("ERROR: Could not connect. " . $mysqli->connect_error);
}
// SQL query execution
$sql = "SELECT * FROM Postcodes";
?>
<!-- Status message -->
<?php if(!empty($statusMsg1)){ ?>
<p class="stmsg"><?php echo $statusMsg1; ?></p>
<?php } ?>
<!-- GENERAL TAB -->
<p style="color:RGB(0,70,135)">You can use the text editor below to display text on your home page</p>
<form action="" method="post">
<div class="form-group">
<label for="postcode1">Enter Postcode Area</label>
<input style="font-size:12px" name="postCodetext" id="postCodetext" class="form-control required" value="e.g CF11">
</div>
<div class="form-group">
<label for="deliveryCost">Delivery Charge</label>
<input style="font-size:12px" name="costtext" id="costtext" class="form-control required" value="e.g 5.00">
</div>
<button type="button" class="save-settings btn btn-primary btn-xs"
title="<?= lang('save') ?>">
<span class="glyphicon glyphicon-floppy-disk"></span>
<?= lang('save') ?>
</button>
<input type="submit" name="submitPostCode" value="Save Data">
</form>
submit.php
<?php
// Include the database configuration file
require_once 'dbConfig.php';
$editorContent = $statusMsg = '';
$postCodeString = $statusMsg1 = '';
// SAVE POSTCODE & DELIVERY COST
if(isset($_POST['submitPostCode'])){
// Get editor content
$postCodeString = $_POST['postCodetext'];
$costString = $_POST['costtext'];
// Check whether the editor content is empty
if(!empty($postCodeString)){
// Insert editor content in the database
$insert1 = $db->query("INSERT INTO PostCodes (postCode, Cost) VALUES ('".$postCodeString."', '".$costString."')");
// If database insertion is successful
if($insert1){
$statusMsg1 = "Succeddfully Saved.";
}else{
$statusMsg1 = "A problem occurred, please try again.";
}
}else{
$statusMsg1 = 'You cannot save a blank postcode or delivery charge';
}
}

I want to update the values but i dont want to change image when i update image is remove

I am updating my form values . Image is already uploaded and can see on the form. When i only update the text value the image is remove and it showing blank.means it does not remains the same when i update it just remove automatically i think not getting the path for current image value when i updating other values. kindly help me to sort out this problem
like if i have to update only name of the person i change the name and other fields remains same. When i click on update all values remains same and also update one which i update but problem is this photo is remove not remain same
<?php
$v_id = $_GET['v_id'];
include "config.php";
$sql = "SELECT * FROM my_veh_ven WHERE v_id='$v_id'";
$result = mysqli_query($conn,$sql);
if(mysqli_num_rows($result)>0)
{
while($row = mysqli_fetch_assoc($result)) {
?>
<!-- form start -->
<form role="form" method="POST" action="updateVehicle.php?v_id=<?= $row["v_id"] ?>" enctype="multipart/form-data">
<div class="box-body">
<div class="form-group col-md-offset-0 col-md-4">
<label for="">25+ Days Rent in PKR</label>
<input type="text" class="form-control" name="v_25_plus_rent" value="<?=$row["v_25_plus_rent"]?>">
</div>
<div class="form-group col-md-offset-0 col-md-8">
<label >Change Vehicle Picture</label>
<input type="file" name="image" id="myFile" value="images/<?=$row["image"]?>" accept="image/*">
</div>
<div class="form-group col-md-offset-0 col-md-4" style="text-align: center;">
<label for="exampleInputFile" style="text-align: center;" >Current Vehicle Picture</label>
<?php echo'<Image src="images/'.$row["image"].'" style="width:325px;height:220px;"></Image>'; ?>
</div>
<div class=" ">
<div class=" with-border" style="text-align:center;">
<h4 class="box-title" style="text-align:center;"><b>Vendor Details</b></h4>
</div>
</div>
</div>
<!-- /.box-body -->
<div class="box-footer skin-yellow">
<button type="submit" name="submit" class="btn btn-primary skin-yellow">Update</button>
</div>
</form>
<?php
}
} else {
echo "Sorry something wrong";
}
mysqli_close($conn);
?>
updating file
<?php
include "config.php";
if(isset($_POST['submit']))
{
$target = "images/".basename($_FILES['image']['name']);
$v_type = $_POST["v_type"];
$v_name = $_POST["v_name"];
$v_man = $_POST["v_man"];
$v_model = $_POST["v_model"];
$v_color = $_POST["v_color"];
$v_trans = $_POST["v_trans"];
$v_1_15_rent = $_POST["v_1_15_rent"];
$v_16_25_rent = $_POST["v_16_25_rent"];
$v_25_plus_rent = $_POST["v_25_plus_rent"];
$v_reg = $_POST["v_reg"];
$vendor_name = $_POST["vendor_name"];
$vendor_mobile = $_POST["vendor_mobile"];
$vendor_price = $_POST["vendor_price"];
$image = $_FILES["image"]["name"];
$v_id=$_GET["v_id"];
$sql = " UPDATE my_veh_ven SET v_type='$v_type', v_name='$v_name' ,v_man='$v_man' ,v_color='$v_color', v_trans='$v_trans', v_1_15_rent='$v_1_15_rent' , v_16_25_rent='$v_16_25_rent' ,v_25_plus_rent='$v_25_plus_rent' , image='$image' , v_reg='$v_reg' ,vendor_name='$vendor_name', vendor_mobile='$vendor_mobile' ,vendor_price='$vendor_price' WHERE v_id='$v_id' ";
if (mysqli_query($conn, $sql))
{
if(move_uploaded_file($_FILES['image']['tmp_name'], $target))
{
$success = "βœ“ Successfully Updated";
}
}
else
{
$fail = "X Not Updated";
}
}
mysqli_close($conn);
?>
Simple Solution while adding put your image name in 1 hidden variable like below
$hiddenImage = $row["image"]
add this hidden variable in your form
<input type='hidden' name='hiddenImage' value='<?php echo $hiddenImage ?>'
and while submit check whether your file input type will contain any data or not. If data/image exist upload this image in folder and same name in db. if image not exist get that input variable save in database.
for e.g :
if (isset($_FILES["image"]["tmp_name"]) && $_FILES["image"]["tmp_name"] != "") {
// upload file and save image name in variable like $imagename
}else{
// if image not upload this code will execute
$imagename = $_POST['hiddenImage'];
}
Save this $imagename variable data in database
An <input type="file"/> has no value attribute usage. The image, once uploaded, is on your server and that's about it. You cannot set the value of the input to anything that would be meaningful.
What you certainly want is to display the uploaded picture instead of the input, and present the input if the user wants to change it.
EDIT: Now that we have your PHP code, we can see that you are overwriting the $image variable even if empty
$image = $_FILES["image"]["name"];
You have to verify if $_FILES["image"] exists, else image will be null or undefined. And then you will update the database with a bad value. I suggest you treat your upload differently than other data:
<?php
include "config.php";
if(isset($_POST['submit']))
{
$target = "images/".basename($_FILES['image']['name']);
$v_type = $_POST["v_type"];
$v_name = $_POST["v_name"];
$v_man = $_POST["v_man"];
$v_model = $_POST["v_model"];
$v_color = $_POST["v_color"];
$v_trans = $_POST["v_trans"];
$v_1_15_rent = $_POST["v_1_15_rent"];
$v_16_25_rent = $_POST["v_16_25_rent"];
$v_25_plus_rent = $_POST["v_25_plus_rent"];
$v_reg = $_POST["v_reg"];
$vendor_name = $_POST["vendor_name"];
$vendor_mobile = $_POST["vendor_mobile"];
$vendor_price = $_POST["vendor_price"];
$v_id=$_GET["v_id"];
$sql = " UPDATE my_veh_ven SET v_type='$v_type', v_name='$v_name' ,v_man='$v_man' ,v_color='$v_color', v_trans='$v_trans', v_1_15_rent='$v_1_15_rent' , v_16_25_rent='$v_16_25_rent' ,v_25_plus_rent='$v_25_plus_rent' , v_reg='$v_reg' ,vendor_name='$vendor_name', vendor_mobile='$vendor_mobile' ,vendor_price='$vendor_price' WHERE v_id='$v_id' ";
if (mysqli_query($conn, $sql))
{
if(move_uploaded_file($_FILES['image']['tmp_name'], $target))
{
$image = $_FILES["image"]["name"];
$success = "βœ“ Successfully Updated";
$sql = "UPDATE my_veh_ven SET image='$image' WHERE v_id='$v_id' ";
mysqli_query($conn, $sql)
}
}
else
{
$fail = "X Not Updated";
}
}
mysqli_close($conn);
?>
There's a simple solution for your problem. Whenever a form submits, check if $_FILES is set/any file is provided or not. If any file/image is provided, then update your database according to it. If the $_FILES array is empty, that means your image/file is not uploaded, and hence you can update it accordingly.
Something like below:
<?php
if(isset($_POST['submit'])){
//check for files or updated variables
if(isset($_FILES)){
//image is provided, now update values accrodingly in your database
echo "image/file provided";
}else{
//image is not uploaded, update other values in database expect image/file
echo "image/file not provided";
}
}else{
?>
<html>
<head><title>My demo form</title></head>
<body>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" enctype="multipart/form-data">
<input type="text" name="data_one">
<input type="file" name="my_file" accept="image/*">
<input type="submit" value="submit">
</body>
</html>
<?php
}
?>

File Not transferring to server

I have a webpage set up that allows for files to be uploaded, the url of the file is saved in the database that works fine, but the file its self is not getting transferred to the server. I am getting a confirmation of the file be saved and the is saving in the database.
Here is a copy of my code.
Any help would be great full.
// Start sessions
include('../inc/security.inc.php');
authorise();
// Include databse connection file
include('../inc/connection.inc.php');
// Check to see if the form has been submitted
if (isset($_POST['submit']))
{
// Check to see all fields have been completed
$target = "../documents/memberDocuments/";
$target = $target . basename(str_replace(' ','_',$_FILES['documentsURL']['name']));
$documentsURL =(str_replace(' ','_',$_FILES['documentsURL']['name']));
$documentsDescription = $_POST['documentsDescription'];
$lessonID = $_POST['lessonID'];
if (!empty($documentsDescription) && !empty($documentsURL) && !empty($lessonID))
{
// Create an SQL query to add the comment
$sql = "INSERT INTO tblDocuments (documentsDescription, documentsURL, lessonID) VALUES ('$documentsDescription', '$documentsURL', '$lessonID')";
// Connect to the database
connect();
// Run the query and store the result in a variable
$result = mysql_query($sql) or die("Could not run query");
if(move_uploaded_file($_FILES['documentsURL']['tmp_name'], $target))
// Close connection to the database
mysql_close();
// Check if query was successful
if ($result)
{
$message = '<div class="success"><p>You have added a new lesson.</p><p>Please Click Here to view all modules.</p></div>';
}
else
{
$message = '<div class="error"><p>There was an error adding your record, please try again</p></div>';
}
}
else
{
$message = '<div class="error"><p>Please make sure you fill all fields in before submitting the form.</p></div>';
}
}
?>
<?php
if (isset($message))
{
echo $message;
}
?>
<form action="<? echo $_SERVER['PHP_SELF']; ?>" method="post" form enctype="multipart/form-data">
<fieldset>
<input type="text" name="documentsDescription" class="text" id="documentsDescription" placeholder="Enter The Lessons Number"></br></br>
<input type="file" name="documentsURL" class="text" id="documentsURL" placeholder="Enter The Lesson Description"></br></br>
<input type="text" name="lessonID" class="text" id="lessonID" placeholder="Enter The Module ID Number"></br></br>
<button type="submit" input type="submit" name="submit" id="submit" class="button iconLeft"><i class="email"></i> Submit</button>
</fieldset>
</form>

PHP OOP Upload file & submit to database with user_id

I'm trying to allow my users to upload a profile picture and display it on their profile.
I've created profilepic.php and added a new function in classes/User.php
So far I'm trying to submit a string via text input and associating it with the current user_id that is logged in.
The function inside 'classes/User.php'
public function uploadPhoto($fields = array()) {
$photo = $this->_db->insert('userPhotos', array('user_id' => $this->data()->id));
if(!$photo) {
throw new Exception('There was a problem creating your account.');
}
}
ProfilePic.php
<?php
require_once 'core/init.php';
include('includes/header.php');
$user = new User();
if(!$user->isLoggedIn()) {
Redirect::to('index.php');
}
if(Input::exists()) {
if(Token::check(Input::get('token'))) {
$validate = new Validate();
$validation = $validate->check($_POST, array(
'url' => array(
'required' => false
)
));
if(!$validation->passed()) {
try {
/* $user->uploadPhoto(array(
'url' => Input::get('url'),
)); */
//This is the directory where images will be saved
$target = 'var/www/app/img';
$target = $target . basename($_FILES['url']['name']);
$pic= ($_FILES['url']['name']);
//Writes the information to the database
//$this->data()->query('INSERT INTO userPhotos (photo) VALUES (β€˜$pic’)');
$user->uploadPhoto(array(
'url' => Input::get($pic)
));
//Writes the photo to the server
if(move_uploaded_file($_FILES['url']['tmp_name'], $target))
{
echo 'Ok' . basename( $_FILES['uploadedfile']['name']);
}
else {
//Gives and error if its not
echo 'Sorry, there was a problem uploading your file.';
}
Session::flash('home', 'Your profile photo has been uploaded.');
Redirect::to('index.php');
} catch(Exception $e) {
die($e->getMessage());
}
} else {
foreach($validation->errors() as $error) {
echo $error, '<br>';
}
}
}
}
?>
<div class="container">
<div class="row row-offcanvas row-offcanvas-right">
<div class="col-xs-12 col-sm-9">
<p class="pull-right visible-xs">
<button type="button" class="btn btn-primary btn-xs" data-toggle="offcanvas">Toggle nav</button>
</p>
<div class="jumbotron">
<h1>Edit Profile</h1>
<p>
<form action="" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="url">URL</label>
<input type="file" id="url" name="url" value="">
<p class="help-block">Example block-level help text here.</p>
<input type="submit" value="Update">
<input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
</div>
</form>
</p>
</div>
<div class="row">
</div><!--/row-->
</div><!--/span-->
<?php include 'includes/sidebar.php'; ?>
</div><!--/row-->
<hr>
<?php include('includes/footer.php'); ?>
userPhotos table has 4 fields: id, user_id (relationship with id in users table), url, date
users table has 6 fields: id, username, password, salt, name, group
So far if I navigate to profilepic.php select a picture and click upload, it will display a success message that my photo has been uploaded. I look into the database, only the row id (auto_increment) and my id (logged_in user id) are being submitted while the "url" field which is supposed to hold the name of the image is not registering.

Categories