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>
Related
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 am working on a code right now that allows for the user to input their email and another user's email to add them as a "friend" into the table "friends"
So far my code works in terms of posting the form data into the DB / table "friends" however the message I would like to appear is not showing up at all.
My HTML form:
<form class="form-signin" action="FriendLookup.php" method = "POST" enctype="multipart/form-data">
<h2 class="form-signin-heading">Add a Friend</h2>
</br>
<label for="inputEmail" class="sr-only">Your Email</label>
<input type="text" id="inputEmail1" name = "self_email" class="form-control" placeholder="Friend's Username" >
</br>
<label class="sr-only">Your Friend's Email</label>
<input type="text" id="inputEmail2" name = "friend_email" class="form-control" placeholder="Your Username" >
</br>
<button class="btn btn-lg btn-primary btn-block" name = "submit" type="submit">Search</button>
</form>
PHP script:
<?php
include_once('support.php');
//connect_database.php contains your connection/creation of a PDO to connect to your MYSQL db on bmgt406.rhsmith.umd.edu/phpmyadmin
include_once('connect_database.php');
ini_set("display_errors","1");
error_reporting(E_ALL);
// Initialize $title and $body.
$title = "Add User";
$body = "<fieldset><legend> $title </legend>";
$name_of_table = "friends";
// Check if the table exists in the db.
if (tableExists($db, $name_of_table)) {
$inputemail1 = $_POST['self_email'];
$inputemail2 = $_POST['friend_email'];
// Prepare a SQL query and bind all 6 variables.
$sqlQuery = "INSERT INTO $name_of_table ( self_email, friend_email)
VALUES ( :self_email, :friend_email)";
$statement1 = $db->prepare($sqlQuery);
$statement1->bindValue(':self_email', $inputemail1, PDO::PARAM_STR);
$statement1->bindValue(':friend_email', $inputemail2, PDO::PARAM_STR);
// Execute the SQL query using $statement1->execute(); and assign the value
// that is returned to $result.
$result = $statement1->execute();
if(!$result) {
// Query fails.
$body .= "Inserting entry for friend failed.";
} else {
// Query is successful.
$body .= "Success";
}
// Closing query connection
$statement1->closeCursor();
}
$body .= "</fieldset>";
echo generatePage($title,$body);
?>
Any help is greatly appreciated. I am a novice programmer.
My function generatePage was wrong. I added HTML into the function and now it works!
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
}
?>
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
I have a form that allows me to edit data in my database. I need to
upload the image to a folder once the form is submitted. This is an edit page and I the way I have it set up is the image name is called from the database and the image is stored in the folder. Can anyone help me?
<?php
// if there are any errors, display them
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<form action="" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<div>
<p><strong>ID:</strong> <?php echo $id; ?></p>
<label> Job Name:</label><br><br>
<input type="text" name="job_name" value="<?php echo $name; ?>"/><br/>
<label></label><br><br>
<label>Job Thumbnail:</label><br><br>
<input id="upload" name="file" type="file" size="10"><br><br>
<input id="filename" type="text" name="job_timg" placeholder="This Fills Automatcially" value="<?php echo $timg; ?>"/><br/>
<label> Job Name:</label><br><br>
<input type="submit" name="submit" value="Submit">
</div>
</form>
</body>
</html>
<?php
}
// connect to the database
include('connect.php');
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// $_FILES["file"]["error"] is HTTP File Upload variables $_FILES["file"] "file" is the name of input field you have in form tag.
// confirm that the 'id' value is a valid integer before getting the form data
if (is_numeric($_POST['id']))
{
// get form data, making sure it is valid
$id = $_POST['id'];
$name = mysql_real_escape_string(htmlspecialchars($_POST['job_name']));
$timg = mysql_real_escape_string(htmlspecialchars($_POST['job_timg']));
// check that name/image fields are both filled in
if ($name == '' || $timg == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
//error, display form
renderForm($id, $name, $timg, $error);
}
else
{
// save the data to the database
mysql_query("UPDATE tbl_job SET job_name='$name', job_timg='$timg' WHERE job_id='$id'")
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: gallery_edit.php");
}
}
else
{
// if the 'id' isn't valid, display an error
echo 'Error!';
}
}
else
// if the form hasn't been submitted, get the data from the db and display the form
{
// get the 'id' value from the URL (if it exists), making sure that it is valid (checing that it is numeric/larger than 0)
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// query db
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM tbl_job WHERE job_id=$id")
or die(mysql_error());
$row = mysql_fetch_array($result);
// check that the 'id' matches up with a row in the databse
if($row)
{
// get data from db
$name = $row['job_name'];
$timg = $row['job_timg'];
// show form
renderForm($id, $name, $timg, '');
}
else
// if no match, display result
{
echo "No results!";
}
}
else
// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
{
echo 'Error!';
}
}
?>
When dealing with files, the form must include a valid enctype.
<form action="" method="post" enctype="multipart/form-data">
For more information on dealing with files, visit the following page on PHP.net:
http://php.net/manual/en/reserved.variables.files.php