when i am edit files,Image file Not uploading his target path - php

I have developed small application with small form,Name and image.
When i am fill the form and click on submit button these form values are stored in database(Name and image path stored in database),and image stored in target folder.
Here is a problem,when i am click on form edit button,edited Name its successfully edited and stored in database.
But when i am browse a image file it's not storing his path into database and image into target folder.
It shows old image path and Image in DB and form.
Here is code.
Form.html
<html>
<form name="files" onsubmit="return formValidator()" action="update.php" method="POST" enctype="multipart/form-data">
<label class="form_label_name">Name<span class="red">*</span>:</label>
<input name="name" type="text" maxlength="32" class="form_input_name" id="form_name" required value="<?php {echo $row['name'];} ?>">
<label class="form_label_image">Grid Image:</label>
<img id="imagetd" class="gridimage" src="<?php {echo $row['thumbnailimage'];} ?>" onclick="getImagePathFromDialog()" />
<label>Click on the image to change the Image</label>
<input type="file" id="imageBrowser" name="imageBrowser" onchange="readURL(this);" style="visibility:hidden;" />
<input type="submit" value="Save" name="submit" class="editfile_save">
</html>
Edit Form:-
update.php:-
<?php
global $nodeid;
global $parentnodeid;
global $user;
global $file_type;
$file_type=$_GET['type'];
$userid=$user->uid;
if(isset($_POST['submit']))
{
$dbhost = 'localhost';
$dbuser = 'xxx';
$dbpass = 'yyy';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
$sqlappidquery = "SELECT appid FROM app WHERE userid=$userid ";
$appidqueryrows = db_query($sqlappidquery, array());
foreach ($appidqueryrows as $appidrow) {
$app_id=$appidrow->appid;
}
if(! get_magic_quotes_gpc() )
{
$name = addslashes ($_POST['name']);
$summary = addslashes ($_POST['summary']);
$url= addslashes ($_POST['urlPath']);
}
else
{
$name = $_POST['name'];
$summary = $_POST['summary'];
$url = $_POST['urlPath'];
}
$target_path = "/sites/default/files/content_images/";
$imagepath=basename( $_FILES['imageBrowser']['name']);
$ext = explode("/", $_FILES['imageBrowser']['type']);
if($ext[0] == 'image')
{
if(empty($imagepath))
{
$target_path =$row['thumbnailimage'];
}
else
{
$target_path = $target_path . basename( $_FILES['imageBrowser']['name']);
}
move_uploaded_file($_FILES['imageBrowser']['tmp_name'], $target_path);
}
else
{
$target_path =$row['thumbnailimage'];
}
?>
Can any one help me on this problem.

<form name="files" onsubmit="return formValidator()" action="update.php" method="POST" enctype="multipart/form-data">
and change your select query like below
$sqlappidquery = "SELECT appid FROM app WHERE userid='".$userid."' ";
user form tag like this

I think u forgot to add enctype="multipart/formdata"

You need to add enctype="multipart/form-data"
and write update code
UPDATE appid SET image='$image' WHERE id='$id';

Related

How to insert images and data into mysql using php?

I am having a trouble to saving data into the database. My connection details and sql insert query everything is correct and image is also uploading to folder but I do not know why data along with image is not saving into an database when i hit upload button.Can anyone help me please?
My php code
<?php
include('server.php');
$userID = 1;
if(isset($_SESSION['username']))
{
$userName = $_SESSION['username'];
$queryID = "SELECT id from users WHERE username = '$userName'";
$resultID = $db->query($queryID);
$row=$resultID->fetch_assoc();
$userID = $row['id'];
}
if(isset($_POST['submit']))
{
$image = $_FILES['image']['name'];
$target = "images/".basename($image);
$eventName = $_POST['eventName'];
$eventDetail = $_POST['eventDetail'];
$eventDate = $_POST['eventDate'];
$eventTime = $_POST['eventTime'];
$queryImage = "INSERT INTO event_detail(eventName,eventDetails,eventDate,eventTime,imagePath,userID) VALUES('$eventName','$eventDetail','$eventDate','$eventTime','$image','$userID')";
mysqli_query($db,$queryImage);
if(move_uploaded_file($_FILES['image']['tmp_name'],$target))
{
$msg = "Image uploaded successfully";
}
else
{
$msg = "There is problem";
}
}
?>
html
<form method="post" enctype="multipart/form-data">
<label for="eventName">Event Name:<label>
<input type="text" id="eventName" name="eventName" ><br><br>
<label for="eventDetail">Event Detail:<label>
<textarea id="eventDetail" name="eventDetail" ></textarea><br><br>
<label for="eventDate">Event Date:<label>
<input type="text" id="eventDate" name="eventDate" ><br><br>
<label for="eventTime">Event Time:<label>
<input type="text" id="eventTime" name="eventTime" ><br><br>
<input type="file" id="image" name="image"><br><br>
<button type="submit" id="submit" name="submit" >Submit</button>
</form>
Change this
$queryImage = "INSERT INTO event_detail(eventName,eventDetails,eventDate,eventTime,imagePath,userID) VALUES ('$eventName','$eventDetail','$eventDate','$eventTime','$image','$userID')";
to
$queryImage = "INSERT INTO event_detail(eventName,eventDetails,eventDate,eventTime,imagePath,userID) VALUES ($eventName,$eventDetail,$eventDate,$eventTime,$image,$userID)";

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

Insert query not working in MySQL , PHP

Here is my code to insert data in MySQL as Back-end and PHP as front-end
Connection is established properly but insert query is not working neither it is showing any error as per the else conditions at the end after insert query
It is not reaching inside the $_POST['submit'] too.
<html>
<head></head>
<title></title>
<body>
<form type="post" name="addimage" enctype="multipart/form-data" >
Album Name<input type="text" name="albumname">
<input type="file" name="filesToUpload" id="filesToUpload" multiple=""/>
</p>
Client Name<input type="text" name="clientname">
<br>Location<input type="text" name="location">
<button type="submit" value="submit" name="submit" id="submit">Submit</button>
</body>
</form>
</html>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "apostrophe";
$con=mysqli_connect("localhost","root","","apostrophe");
mysqli_select_db($con,"apostrophe");
if(isset($_POST['submit']))
{
echo "reached";
$albumname=$_REQUEST['albumname'];
$images=$_REQUEST['filesToUpload'];
$client=$_REQUEST['clientname'];
$loc=$_REQUEST['loc'];
echo "reached submit";
$sql="INSERT INTO album(albumname,images,clientname,location)VALUES('$albumname','$albumname','$client','$loc')";
echo "reached down";
if($con->query($sql)===TRUE)
{
echo "Success";
}
else
echo "Failed";
}
?>
The original code has quite a few errors in ( the form straddles the body, wrong declaration for form method, title outside the head etc ) and there is no attempt at handling the actual uploaded images. Hopefully the following ought to give you a headstart with getting the file handling piece completed - though no doubt I have missed something too '-)
<?php
$status='';
/* Might as well test that all necessary fields are included in form submission */
if( isset( $_POST['submit'], $_POST['albumname'], $_POST['clientname'], $_POST['location'] ) ){
/* only need to declare the db connection if the variables are set */
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "apostrophe";
/* create the db conn */
$con=mysqli_connect("localhost","root","","apostrophe");
/* at least some basic filtering if you intend to place user submitted content directly in the sql */
$albumname=strip_tags( filter_input( INPUT_POST,'albumname',FILTER_SANITIZE_STRING ) );
$client=strip_tags( filter_input( INPUT_POST,'clientname',FILTER_SANITIZE_STRING ) );
$loc=strip_tags( filter_input( INPUT_POST,'location',FILTER_SANITIZE_STRING ) );
/* handle file uploads */
$fieldname='filesToUpload';
foreach( $_FILES[$fieldname]['name'] as $i => $name ) {
if( !empty( $_FILES[$fieldname]['tmp_name'][$i] ) ) {
$filename = $_FILES[$fieldname]['name'][$i];
$size = $_FILES[$fieldname]['size'][$i];
$type = $_FILES[$fieldname]['type'][$i];
$tmpfile = $_FILES[$fieldname]['tmp_name'][$i];
/* copy file to final destination - this is not complete!! */
$bytes=move_uploaded_file( $tmpfile, '/path/to/final/directory/'.$filename );
/* to debug uncomment below */
#echo $filename,$tmpfile,$size,$type;
}
}
/* prepare and execute sql */
$sql="INSERT INTO `album` ( `albumname`, `images`, `clientname`, `location` ) VALUES ( '$albumname', '$albumname', '$client', '$loc' )";
/* set status variable to be displayed under form */
$status=( $con->query( $sql )===TRUE ) ? "Success" : "Failed";
} else {
$status='bad foo';
$status=print_r( $_POST, true );
}
?>
<html>
<head>
<title>File upload and database inserts</title>
</head>
<body>
<form method="post" name="addimage" enctype="multipart/form-data" >
Album Name<input type="text" name="albumname">
<input type="file" name="filesToUpload[]" id="filesToUpload" multiple=""/>
Client Name<input type="text" name="clientname">
<br>
Location<input type="text" name="location">
<button type="submit" value="submit" name="submit" id="submit">Submit</button>
</form><?php echo $status; ?>
</body>
</html>
Change your line :
<form type="post" name="addimage" enctype="multipart/form-data">
to
<form method="post" name="addimage" enctype="multipart/form-data">

PHP file upload into mysql

I have created a form as follows. What I'm doing is
User is selecting a client from drop down list and uploading file. When he clicks on Add button the page will redirect to Confirm.php.
The Confirm.php will show whatever the user has given the input i.e, Client name and name of the file which he has uploaded.
In Confirm.php the user is submitting the form and it should add to the database, except file upload remaining fields are adding to the database. In database, file upload field is showing empty. Please somebody solve this problem.
And I'm not getting how to access path variable from Confirm.php into Add.php.
I'm new to the php. So any help will be appreciated.
Thank you.
Home.php
<form action="Confirm.php" method="post" enctype="multipart/form-data" novalidate>
<label> <span>Client</span>
<select class="required" name="client">
<?php
mysql_connect ("localhost","root","");
mysql_select_db ("eservice");
$select="eservice";
if (isset ($select)&&$select!="")
{
$select=$_POST ['NEW'];
}
?>
<?php
$list=mysql_query("select * from client");
while($row_list=mysql_fetch_assoc($list))
{
?>
<?php $ct = $row_list['cname'];?>
<option value="<?php echo $ct; ?>"<?php if($ct==$select){ echo "selected"; } ?> > <?php echo $ct; ?></option>
<?php } ?>
</select>
</label>
<label> <span>SRN</span>
<?php
$con=mysqli_connect("localhost","root","","eservice");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="Select * from main";
if ($result=mysqli_query($con,$sql))
{
// Return the number of rows in result set
$rowcount=mysqli_num_rows($result);
$rowcount++;
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
?>
<input name="srn" type="text" id="srn" size="15" readonly="readonly" maxlength="40" value="<?php echo "$rowcount"; ?>"/>
</label>
</div>
<label>
<span>File upload</span>
<input type="file" name ="filename" required>
</label>
<button id='send' type='submit'>Add</button>
<button id='clear' type='reset'>Reset</button>
</form>
And this is my cofirmation page
Confirm.php
<form action="Add.php" method="post" enctype="multipart/form-data" novalidate>
<label> <span>Client</span>
<?php include_once('dbconn.php'); ?>
<input name="client" type="text" id="client" size="15" readonly="readonly" maxlength="40" value="<?php echo $_POST['client']; ?>"/>
</label>
<label>
<span>File upload</span>
<?php $path = '';
$folder = "Folder/";
if (is_uploaded_file($_FILES['filename']['tmp_name']))
{
if (move_uploaded_file($_FILES['filename']['tmp_name'], $folder.$_FILES['filename']['name']))
{
$path = $folder . $_FILES['filename']['name'];
}
else
{
$path = '';
};
}
else
{
$path = '';
}; ?>
<input name ="filename" readonly="readonly" value="<?php echo $_FILES['filename']['name']; ?>"/>
</label>
<button id='clear' type='reset'>Back</button>
<button id='send' type='submit'>Add</button>
</form>
dbconn.php
<?php
$username = "root";
$password = "";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$selected = mysql_select_db("eservice",$dbhandle)
or die("Could not select newsite database");
?>
Here I'm adding the uploaded file into the phpmyadmin.
Add.php
<?php
include_once('dbconn.php');
session_start();
$_SESSION['example']='Session Created';
$client = $_POST['client']; // required
if($client !='')
{
$insQry = "Insert into `main` (client,upload) Values ('$client','$path')";
$insertQ = mysql_query($insQry);
if($insertQ!=''){
echo "<h2>Data inserted successfully...</h2>";
} else {
echo "<h2>Not added</h2>";
}
}
?>
Undefined Index means if that index is not set or empty...you have to check is it empty or not.
add condition in filename error
if ( $_FILES['filename']['error'] == 0 ){
///your uploading code
}
and for post veriable check it is isset or not, use ternary operator:-
$client =isset( $_POST['client'])?$_POST['client']:'';
Your confirm.php code should be
<form action="Add.php" method="post" enctype="multipart/form-data" novalidate>
<label> <span>Client</span>
<?php include_once('dbconn.php'); ?>
<input name="client" type="text" id="client" size="15" readonly="readonly" maxlength="40" value="<?php echo $_POST['client']; ?>"/>
</label>
<label>
<span>File upload</span>
<?php $path = '';
$folder = "Folder/";
if (is_uploaded_file($_FILES['filename']['tmp_name']))
{
if (move_uploaded_file($_FILES['filename']['tmp_name'], $folder.$_FILES['filename']['name']))
{
$path = $folder . $_FILES['filename']['name'];
}
else
{
$path = '';
};
}
else
{
$path = '';
}; ?>
<input name ="filename" readonly="readonly" value="<?php echo $_FILES['filename']['name']; ?>"/>
<input name ="path" type="hidden" value="<?php echo $path; ?>"/>
</label>
<button id='clear' type='reset'>Back</button>
<button id='send' type='submit'>Add</button>
</form>
You can get your hidden field value on add.php using $path = $_POST['path']

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>

Categories