PHPmailer sending email with Attachment - php

I have a script for sending emails with PHPmailer (the class is different because I use a CRUD but the functions are the same)
This is the script:
if (array_key_exists('recipient', $_POST)) {
$attachment = tempnam(sys_get_temp_dir(), hash('sha256', $_FILES['attachment']['name']));
move_uploaded_file($_FILES['attachment']['tmp_name'], $attachment);
$recipient = $_POST['recipient'];
$subject = $_POST['subject'];
$content = $_POST['content'];
//$attachment = $_POST['attachment'];
$email->Sender = "noreply#fw.net";
$email->Recipient = "noreply#fw.net";
if (!empty($_POST['recipient'])) {
$email->Recipient = $recipient;
} else {
foreach ($bcc as $bcc) {
$email->addBcc($bcc);
}
}
//$email->addRecipient = $bcc;
$email->Subject = $subject;
$email->Content = $content;
$email->addAttachment($attachment, 'MyFile');
$email->Format = "html";
//$email->send();
if(!$email->send()) {
$msg = '<div style="Color:red">Sent:</div>'. $email->SendErrDescription;
} else {
$msg = '<div style="Color:green">not Sent</div>';
header("Refresh:5");
}
}
this the form: email.php (work on the same page script / form)
<form id="mess" action="email.php" method="POST" enctype="multipart/form-data">
<?php if ($Page->CheckToken) { ?>
<input type="hidden" name="<?php echo TOKEN_NAME ?>" value="<?php echo $Page->Token ?>">
<?php } ?>
<div id="jsInfo" data-count="<?php echo $count; ?>"></div>
<div class="card card-primary card-outline">
.......
<div class="form-group">
<div class="btn btn-default btn-file">
<i class="fa fa-paperclip"></i> Allegato
<input type="hidden" name="MAX_FILE_SIZE" value="100000"> <input type="file" name="attachment" id="attachment">
</div>
<p class="help-block">Max. 10MB</p>
</div>
........
<button type="submit" value="Upload" name="submit" class="btn btn-primary"><i class="fa fa-envelope-o"></i> Send </button>
I changed the destination to php.ini I use wamp in local for testing
from:
sys_temp_dir = "/tmp"
to
sys_temp_dir = "c:/Users/lt/Documents/Temp"
Question:
Why is not attached to the original file(pdf,jpg,bmp,txt ecc..), but the *.tmp file is attached. ? where am I wrong?
let's say I solved that.
don't works
$attachment = tempnam(sys_get_temp_dir(), hash('sha256', $_FILES['attachment']['name']));
move_uploaded_file($_FILES['attachment']['tmp_name'], $attachment);
works
$uploaddir = 'C:/wamp64/www/fw3/';
$attachment_tmp = $_FILES['attachment']['tmp_name'];
$attachment_name = $_FILES['attachment']['name'];
move_uploaded_file($attachment_tmp, $uploaddir . $attachment_name);
I have two problems again ...
1) How to send the attachment to all recipients?
2) When sending a 4Mb file the page loads a lot of time, how can I modify the script to make the sending work in the background?

Related

Set column as empty if no file is selected when submit

I am very new to PHP and was trying to do the file uploading. When I try to submit a form without having any files selected, the database will still insert a value to the attachments column.
My table picture:
Is there any way that I can set the attachments column as empty if there is not file selected for submission. Below is my code:
view_group.php
<form class="forms-sample" enctype='multipart/form-data' method="post">
<div class="modal-body">
<div class="form-group">
<textarea id="status_content" name="status_content" rows="30"></textarea>
</div>
<div class="form-group">
<label for="section_label">Add Attachments</label><br>
<input type="text" class="form-control" id="file" disabled placeholder="Select a file"><br>
<button type="button" class="file-upload-browse btn btn-primary" name="button" onclick="document.getElementById('fileName').click()">Select a file</button>
<input type="file" name="attachmentfile" id="fileName" style="display:none">
</div>
</div>
<div class="modal-footer">
<button class="btn btn-outline-secondary btn-fw">Cancel</button>
<input type="submit" class="btn btn-primary" name="postStatus" value="Post" />
</div>
</form>
GroupsController.php
function postStatus($std_id, $group_id){
$status = new ManageGroupsModel();
$status->std_id = $std_id;
$status->group_id = $group_id;
$status->status_content = $_POST['status_content'];
$status->attachments = time() . $_FILES['attachmentfile']['name'];
$status->target_dir = "../../attachments/groupfiles/";
//target file to save in directory
$status->target_file = $status->target_dir . basename($_FILES["attachmentfile"]["name"]);
// select file type
$status->imageFileType = strtolower(pathinfo($status->target_file,PATHINFO_EXTENSION));
// valid file extensions
$status->extensions_arr = array("jpg","jpeg","png","gif","pdf", "doc", "pdf");
if($status->postStatus() > 0) {
$message = "Status posted!";
echo "<script type='text/javascript'>alert('$message');
window.location = '../ManageGroupsView/view_group.php?group_id=".$group_id."'</script>";
}
}
GroupsModel.php
function postStatus() {
$sql = "insert into status(std_id, group_id, status_content, attachments) values(:std_id, :group_id, :status_content, :attachments)";
$args = [':std_id'=> $this->std_id, ':group_id'=> $this->group_id, ':status_content'=> $this->status_content, 'attachments'=> $this->attachments];
move_uploaded_file($_FILES['attachmentfile']['tmp_name'],$this->target_dir.$this->attachments); $stmt = DB::run($sql, $args);
$count = $stmt->rowCount(); return $count; }
I'm sorry if the question sounded dumb. It would be really great if someone can help. Thank you!
UPDATE!
Thanks to the people in my comment section, I finally get to do it. Here are the code needed to add :
function postStatus($std_id, $group_id){
$status = new ManageGroupsModel();
$status->std_id = $std_id;
$status->group_id = $group_id;
$status->status_content = $_POST['status_content'];
if($_FILES['attachmentfile']['name']) {
$status->attachments = time() . $_FILES['attachmentfile']['name'];
$status->target_dir = "../../attachments/groupfiles/";
//target file to save in directory
$status->target_file = $status->target_dir . basename($_FILES["attachmentfile"]["name"]);
// select file type
$status->imageFileType = strtolower(pathinfo($status->target_file,PATHINFO_EXTENSION));
// valid file extensions
$status->extensions_arr = array("jpg","jpeg","png","gif","pdf", "doc", "pdf");
} else {
$status->attachments = '';
}
if($status->postStatus() > 0) {
$message = "Status posted!";
echo "<script type='text/javascript'>alert('$message');
window.location = '../ManageGroupsView/view_group.php?group_id=".$group_id."'</script>";
}
}

PhpMailer: could not access file error, while sending upload file from tmp directory as attachment

I am trying to send the file which is uploaded and gets saved to tmp directory as an attachment. I am using PhPMailer but i am getting Could not access file error. The mail is getting sent with text in it on clicking submit but file which gets uploaded is not getting sent. I have gone through similar type of asked questions but none could solve the issue.
Here is the code.
<?php
if(isset($_POST['submit'])){
include('PHPMailer_5.2.0/class.phpmailer.php');
$content = 'Hello world!';
$email = new PHPMailer();
$email->From = 'info#example.com';
$email->FromName = 'Your Name';
$email->Subject = 'Subject';
$email->Body = $content;
$email->AddAddress( 'xxx#gmail.com' );
$email->AddAttachment( $_FILES['fileUpload']['tmp_name'], $_FILES['fileUpload']['name'] );
return $email->Send();
}
?>
<html>
<head>
<body>
<form id="sunrise" name="sunrise" method="post" action="">
<div class="form-group uploader col-xs-4">
<label class="coole" id="no-print">Upload Child's Image:</label>
<input name="fileUpload" type="file" id="fileUpload" class="no-print" required />
<br />
<div name="image-holder" id="image-holder"> </div>
</div>
<div class="col-xs-4">
<input type="text" name="student_name" class="form-control" id="add_student_first_name" placeholder='Your Name' required>
</div>
<button type="submit" class="btn btn-default" id="no-print" name="submit" value="submit">Submit</button>
</form>
<script>
$("#fileUpload").on('change', function() {
if (typeof(FileReader) != "undefined") {
var image_holder = $("#image-holder");
image_holder.empty();
var reader = new FileReader();
reader.onload = function(e) {
$("<img />", {
"src": e.target.result,
"class": "thumb-image",
"width": "113px",
"height": "151px"
}).appendTo(image_holder);
}
image_holder.show();
reader.readAsDataURL($(this)[0].files[0]);
} else {
alert("This browser does not support FileReader.");
}
});
</script>
<script type="text/javascript">
document.getElementById('date').valueAsDate = new Date();
</script>
</body>
</html>

How to upload a profile picture using a form post to slim framework accepting and moving the file to a folder?

I am using a form that posts a profile picture, then a functions file which parses the data and sends it to a rest service which is developed with the slim framework.
Here is my code:
form.php:
<form action="<?php echo url('functions.php'); ?>" method="post" class="validate form-horizontal">
<input type="hidden" name="action" value="save_account_settings">
<div class="form-group">
<label class="col-sm-3 control-label"><span class="colordanger">*</span>Profile picture</label>
<div class="col-sm-9">
<input type="file" name="profile_picture" class="form-control" value="<?php echo $user->profile_picture; ?>" data-rule-required="true">
<span class="help-block">Upload your profile picture here</span>
</div>
</div>
<div class="form-group">
<div class="col-sm-9 col-sm-offset-3">
<button type="submit" class="btn btn-primary" data-loading-text='<i class="fa fa-spinner fa-spin"></i> Saving...'><i class="fa fa-check"></i> Save</button>
</div>
</div>
</div>
</form>
functions.php:
case 'save_account_settings':
try {
$input = array (
"profile_picture" => "#" . post('profile_picture')
);
$extension = '/save_account_settings';
$result = process_api_put($input,$base_url,$extension);
msg($result->message, $result->status);
}
catch (Exception $e)
{
msg($e->getMessage(), "danger");
}
break;
And then rest.php:
$app->put("/save_account_settings", function() use ($app)
{
$input = $app->request()->getBody();
$input = json_decode($input);
try {
if ($input->username && $input->email)
{
//save the file
$file_extension = pathinfo($input->profile_picture, PATHINFO_EXTENSION);
$server_file_address = realpath('./') . '/uploads/profile_pictures/' . $_SESSION['id'] . date('Y-m-d H:i:s') . $file_extension;
move_uploaded_file( $input->profile_picture, $server_file_address );
//save to database
$users = Model::factory('Users')->where('id', $_SESSION['id'])->find_one();
$users->set('profile_picture', '/uploads/profile_pictures/' . $_SESSION['id'] . date('Y-m-d H:i:s') . $file_extension);
$users->save();
$status = "success";
$message = 'Your settings have been saved successfully.';
}
else
{
$status = "danger";
$message = 'Some error has occured. Please try again.';
}
}
catch (Exception $e)
{
$status = "danger";
$message = $e->getMessage();
}
$response = array(
'status' => $status,
'message' => $message
);
$app->response()->header("Content-Type", "application/json");
echo json_encode($response);
});
It saves the filename in the database but doesnot save the file in the uploads directory. Does anyone see where I am going wrong?

Paypal button Integration within a form

I am stuck in bit of a situation here. So the issue is that I have a simple form which gets the data using $_POST and emails the data to a email (I am using PHPMailer). Now I have to integrate a Paypal button in it so that the client could be redirected to the Paypal page for payment, the issue is that the Paypal button is a form and it has its own action and I am not sure how to apply both (Paypal and Emailing) actions together in the same form. Can someone please guide me here?
Emailing Form:
<form action="process-email.php" class="floatfix" id="card-form" method="post" data-message="Thank you for purchasing. We will contact you via email." enctype="multipart/form-data">
<div class="flt-l left">
<div class="field-container">
<div class="field-number">1</div>
<h3 class="txt-a-c h3-title"><img src="img/icons/clipboard.png" alt="">Place your Order</h3>
<div class="form-panels floatfix clr-b">
<div class="flt-l left-side-panel">
<div id="form-contact-details-container" class="form-contact-details-container">
<input type="text" tabindex="10" required value="Full Name" name="full-name">
<input type="text" tabindex="20" required value="Office #" name="office">
<input type="text" tabindex="30" required value="Mobile #" name="mobile">
<input type="text" tabindex="40" required value="Email" name="email">
<input type="text" tabindex="50" required value="Website" name="website">
</div>
<div class="card-styles floatfix">
Card Style
</div>
<div class="card-shots">
<div class="card-shot pos-r floatfix">
<input type="radio" name="body_shots" id="card-shot-none" data-card-shot-type="none" value="Full Shot" checked class="active">
<span class="radio">No <br>Shot</span>
<img src="img/card_empty.png" alt="" class="card-empty-img">
<div class="check-mark"><img src="img/icons/check_round.png" alt=""></div>
</div>
<div class="card-shot pos-r floatfix">
<input type="radio" name="body_shots" id="card-shot-half" data-card-shot-type="half" value="Half Shot">
<span class="radio">Half Body <br>Shot</span>
<img src="img/card_half_pic.png" alt="">
<div class="check-mark"><img src="img/icons/check_round.png" alt=""></div>
</div>
<div class="card-shot pos-r floatfix">
<input type="radio" name="body_shots" id="card-shot-full" data-card-shot-type="full" value="Full Shot">
<span class="radio">Full Body <br>Shot</span>
<img src="img/card_full_pic.png" alt="">
<div class="check-mark"><img src="img/icons/check_round.png" alt=""></div>
</div>
</div>
<div id="upload-container" class="noselect notify-hover upload-container">
<div class="inner">
<div id="upload-preview" class="page-cover upload-img-container"></div>
<div class="upload-text">Upload Your Photo <span class="camera"></span></div>
<input id="upload-file" class="upload-file" type="file" name="upload-file[]" multiple="multiple">
</div>
<div class="notify">
<h6 class="fnt-w-b">Only Upload files less than 2mb.</h6>
<p>Please allow 2 Business Days for Photo Filtering and Processing.</p>
</div>
</div>
<div class="pos-r notify-hover shipping-address">
<input id="shipping-address-1" type="text" placeholder="Shipping Address" tabindex="60" name="shipping_address_1">
<span id="shipping-address-1-holder" class="pos-a hidden"></span>
<input id="shipping-address-2" type="text" tabindex="70" name="shipping_address_2">
<span id="shipping-address-2-holder" class="pos-a hidden"></span>
<div class="notify">
<p>Carefully Fill this as we do not offer refund on lost packages.</p>
</div>
</div>
</div>
<div class="flt-r right-side-panel">
<span class="noselect crs-p card-flipper">See <span data-before="Back" data-after="Front"></span> of Card</span>
<div class="pos-r">
<div id="the-card" class="noselect card-preview-container">
<div class="card card-front">
<div class="full-before full-after card-pic"></div>
<div id="card-detail-preview-container" class="card-detail-preview noselect crs-d"></div>
</div>
<div class="card card-back"><img src="img/card_back.png" alt=""></div>
</div>
</div>
</div>
</div>
<div class="submit-button-container">
<input type="submit" value="" id="card-form-submit">
<div class="submit-button">
<h2 class="txt-t-u">$125 - Order Now</h2>
<div>1000 Business Cards</div>
</div>
<img src="img/paypal.png" alt="" class="paypal">
<p class="small txt-a-c">You will be takend to Paypal for payment processing</p>
</div>
</div>
</div>
<div class="flt-r right">
<div class="field-container">
<div class="field-number">2</div>
<div class="checkbox-container">
<div class="checkbox">
<img src="img/icons/check.png" alt="">
</div>
<span class="label">Approve & Receive It</span>
</div>
<p class="p-1">You will receive a PDF of the final card with your processed photo.</p>
<p class="p-2">You will receive your order within 7-10 business days.</p>
</div>
</div>
</form>
PayPal Form:
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="KJU58">
<input type="image" src="http://www.deadlyfishesmods.com/wp-content/uploads/2013/09/Buy-Now-Button.png" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">
<img alt="" border="0" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" width="1" height="1">
</form>
Process-email.php:
<?php
if(isset($_POST['full-name'])) {
require 'includes/PHPMailerAutoload.php';
require 'includes/config.php';
$smtp_host = $config["SMTP_HOST"];
$email = $config["EMAIL"];
$email_password = $config["EMAIL_PASSWORD"];
$email_subject = $config["EMAIL_SUBJECT"];
$name = $_POST['full-name']; // required
$office = $_POST['office']; // required
$mobile = $_POST['mobile']; // required
$user_email = $_POST['email']; // required
$website = $_POST['website']; // required
$card_type = $_POST['body_shots'];
$address_1 = $_POST['shipping_address_1'];
$address_2 = $_POST['shipping_address_2'];
$email_exp = '/^[A-Za-z0-9._%-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$email_message = "You have a new card order. <br/> <br/>";
$email_message .= "Name: ".clean_string($name)."<br/>";
$email_message .= "Office: ".clean_string($office)."<br/>";
$email_message .= "Mobile Number: ".clean_string($mobile)."<br/>";
$email_message .= "Email: ".clean_string($user_email)."<br/>";
$email_message .= "Website: ".clean_string($website)."<br/>";
$email_message .= "Card Type: ".clean_string($card_type)."<br/>";
$email_message .= "Address: ".clean_string($address_1) . clean_string($address_2) . "<br/>";
$mail = new PHPMailer(); // create a new object
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 0; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for GMail
$mail->Host = "$smtp_host";
$mail->Port = 465; // or 587
$mail->IsHTML(true);
$mail->Username = "$email";
$mail->Password = "$email_password";
$mail->Subject = "$email_subject";
$mail->Body = $email_message;
$validAttachments = array();
if($card_type !== "Full Shot"){
foreach($_FILES['upload-file']['name'] as $index => $fileName) {
$filePath = $_FILES['upload-file']['tmp_name'][$index];
$validAttachments[] = array($filePath, $fileName);
}
foreach($validAttachments as $attachment) {
$mail->AddAttachment($attachment[0], $attachment[1]);
}
}
$mail->AddAddress("example#sample.com");
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
$counter = 1;
foreach($validAttachments as $attachment) {
move_uploaded_file( $attachment[0], "uploads/" . clean_string($name) . "_" . $counter . "_" . rand() . "_" . $attachment[1] );
$counter++;
}
}
}
You can have the paypal url as your form's action and use Ajax to save or email the form data before the form is submitted to Paypal. You can also use the Ajax response to prepare the form before submission, e.g. filling some hidden fields
Here's an example:
myform.php:
<form id="myform" method="post" action="<?php echo $paypal_url; ?>">
<input type="text" ...>
<input type="hidden" name="my-hidden-field" id="my-hidden-field" value="this is hidden">
...other form fields...
</form>
saveform.php: Processes the Ajax request and returns a response that can be used to manipulate the form before submission
<?php
if (!empty($_POST)) {
//save $_POST data to the database
//or insert your email code portion here
...
//also, fill some data as response
$response = array('my_hidden_field' => 'this is now filled in');
//next line returns the response
echo json_encode($response);
}
myform.js: Submits form data to saveform.php before submitting to paypal
$j = jQuery.noConflict();
$j(document).ready(function() {
$j('#myform').submit(submit_myform);
});
function submit_myform() {
if (!myform_is_valid()) {
window.location.href = "#myform";
return false;//prevent normal browser submission, to display validation errors
} else {
$j.ajax({
url: 'saveform.php',
type: 'POST',
data: $j(this).serialize(),
dataType:'json', //data type of Ajax response expected from server
success: myform_success //callback to handle Ajax response and submit to Paypal
});
return false;//prevent normal browser submission, since the form is submitted in the callback
}
}
function myform_is_valid() {
$valid = true;
//validate data; if there's a validation error, set $valid=false and display errors on page
...
return $valid;
}
function myform_success(response) {
//this is called whenever the ajax request returns a "200 Ok" http header
//manipulate the form as you wish
$j('#my-hidden-field').val(response.my_hidden_field);
//submit the form (to the form's action attribute, i.e $paypal_url)
document.forms['myform'].submit();
}
Instead of the jquery.ajax call you can also use the shorter:
$j.post('saveform.php',$j('#myform').serialize(),myform_success,"json")
This is to give you an idea of how you can accomplish both in one submit action.

Ajax Form Error submitting an image

I'm having a difficult time trying to make AJAX edit changes when the form is submitted on the same page and make the changes appear, but the image throws error: Undefined index: image in update.php on line 22 and 24. It refuses to pass the values.
Form (editForm.php):
<div class="modal-content editDisplay">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="editModalLabel">Edit Item</h4>
</div>
<form class="editForm" method="post" enctype="multipart/form-data">
<div class="modal-body">
<div class="form-group">
<label for="inputName">Name</label>
<input type="text" class="form-control" id="inputName" name="Product_Name" placeholder="Name" value="<?php echo $product ?>">
<input type="hidden" name="oldProduct" value="<?php echo $oldProduct ?>">
</div>
<div class="form-group">
<label for="inputDescription">Description</label>
<textarea class="form-control" id="inputDescription" name="Description" placeholder="Description"><?php echo $description ?></textarea>
</div>
<div class="form-group">
<label for="inputPrice">Price</label>
<input type="text" class="form-control" id="inputPrice" name="Price" placeholder="Price" value="<?php echo $price ?>">
</div>
<div class="form-group">
<label for="inputQuantity">Quantity</label>
<input type="number" class="form-control" id="inputQuantity" name="Quantity" placeholder="Quantity" value="<?php echo $quantity ?>">
</div>
<div class="form-group">
<label for="inputSalePrice">Sale Price</label>
<input type="text" class="form-control" id="inputSalePrice" name="Sale_Price" placeholder="Sale Price" value="<?php echo $salePrice ?>">
</div>
<div class="form-group">
<label for="inputImage">Image Upload</label><br>
<fieldset class="file-fieldset">
<span class="btn btn-default btn-file">
<span class="glyphicon glyphicon-upload"></span> Browse Browse <input name="image" type="file" id="inputImage"/><br>
</span>
<input type="hidden" name="prevPicture" value="<?php $image ?>"/>
<span style="margin-left:8px;" value=""><?php echo $image ?></span>
</fieldset>
</div>
</div>
<div class="modal-footer">
<button type="reset" class="btn btn-default">Reset</button>
<button type="submit" class="btn btn-primary" id="saveButton" name="update">Save Changes</button>
</div>
</form>
</div>
PHP (update.php):
<?php
include('connection.php');
include('LIB_project1.php');
$productName = $_POST['Product_Name'];
$productDescription = $_POST['Description'];
$price = $_POST['Price'];
$quantity = $_POST['Quantity'];
$salePrice = $_POST['Sale_Price'];
$oldImage = $_POST['prevPicture'];
$oldProduct = $_POST['oldProduct'];
//$productName = 'Jaime';
//$productDescription = 'This is crazy';
//$price = '0';
//$quantity = '12234';
//$salePrice = '0';
//$oldImage = $_POST['prevPicture'];
//$oldProduct = $_POST['oldProduct'];
$imageName= $_FILES['image']['name']; //TODO line 22
echo ' The image is '.$imageName;
$image_temp = $_FILES['image']['tmp_name']; // line 24
echo 'Product name is: '.$productName;
//$productName = 'Dodo Square';
//$productDescription = 'Flower on a Bee. Such Beauty!';
//$price = 9;
//$quantity = 8;
//$salePrice = 230;
//$newImage = '038.jpg';
//$oldProduct = 'Times Square';
//working under the assumption that the image already exist in the database
$targetDirectory = 'productImages';
$files = scandir($targetDirectory,1);
//code passed
for($i=0; $i<sizeof($files); $i++)
{
if($oldImage==$files[$i])
{
unlink('productImages/'.$oldImage);
}
}
$target = "productImages";
//add the image to the directory
$target = $target.'/'.$imageName;
move_uploaded_file($image_temp,$target);
updateProduct($conn,'product',':productName', ':productDescription', ':price', ':quantity', ':imageName', ':salePrice', 'Product_Name', 'Description', 'Price', 'Quantity', 'Image_Name', 'Sale_Price', $productName, $productDescription, $price, $quantity,$imageName, $salePrice, $oldProduct, ':oldProduct');
//header('location:admin.php');
?>
updateProduct(...)
/*
* This is a function to update Product
*
*/
function updateProduct(PDO $connection,$table,$bindProductName, $bindProductDescription, $bindPrice, $bindQuantity, $bindImageName, $bindSalePrice,$productNameColumn, $productDescriptionColumn, $priceColumn, $quantityColumn, $imageNameColumn, $salePriceColumn, $productName, $productDescription, $price, $quantity, $imageName, $salePrice, $oldProduct, $bindOldProduct)
{
$result = false;
$sql = 'UPDATE ' . $table . ' SET ' . $productNameColumn . ' = ' . $bindProductName . ',' . $productDescriptionColumn . ' = ' . $bindProductDescription . ',' . $priceColumn . ' = ' . $bindPrice . ',' . $quantityColumn . ' = ' .
$bindQuantity . ',' . $salePriceColumn . ' = ' . $bindSalePrice . ',' . $imageNameColumn . ' = ' . $bindImageName . ' WHERE ' . $productNameColumn . ' = ' . $bindOldProduct;
$smtp = $connection->prepare($sql);
$smtp -> bindParam($bindProductName, $productName);
$smtp -> bindParam($bindProductDescription, $productDescription);
$smtp -> bindParam($bindPrice, $price);
$smtp -> bindParam($bindQuantity, $quantity);
$smtp -> bindParam($bindImageName, $imageName);
$smtp -> bindParam($bindSalePrice, $salePrice);
$smtp -> bindParam($bindOldProduct, $oldProduct);
if($smtp->execute() )
{
$result = true;
}
return $result;
}
AJAX (display edited changes) Problem: Need to submit those edited changes
$(document).ready(function()
{
//the user click save edit
$(".edit").on("submit",function(e)
{
e.preventDefault();
$.ajax({
type:"POST",
url:'update.php', //I will put project id here as well
data:$(".editForm").serialize(),
success:function(smsg)
{
alert(smsg);
//update the number of items the user has in their shopping cart
$.get('admin.php',function(data){
$('#refresh').load("admin.php #refresh");
//alert('success');
});
}
});
});
});
var inputImage = $("#inputImage");
var fd = new FormData(document.getElementById("editform"));
fd.append("image", inputImage);
$.ajax({
url: "",
type: "POST",
data: fd,
processData: false,
contentType: false,
success: function(response) {
}
});
By default the image is not being added to the form during your post, you need to get the entire form and append the image to it before sending it. I did this for asp.net, it should work for php too though.
Add a series of tests to your PHP and you'll figure it out quite quickly yourself.
You are already alerting the response sent by the PHP ajax processor file:
alert(smsg);
So, use that to troubleshoot/diagnose where things are going wrong.
First test can be to put a "I got here" message at the top of the PHP file -- at least then you know the ajax itself is working. So, modify the top of update.php to read:
<?php
echo "Got to here";
die();
If that alerts, then get rid of the die() and echo out a few more such tests at various places in the file. Use this method to narrow down the location (in the PHP file) of the error.
Echo out the data received so you know what is coming in. Modify update.php to be:
$productName = $_POST['Product_Name'];
$productDescription = $_POST['Description'];
$price = $_POST['Price'];
$quantity = $_POST['Quantity'];
$salePrice = $_POST['Sale_Price'];
$oldImage = $_POST['prevPicture'];
$oldProduct = $_POST['oldProduct'];
echo "$productName: " .$productName. " -- $productDescription: " .$productDescription. " - etc etc etc";
die();
I'm sure you'll find the error pretty quick -- certainly quicker than composing a detailed SO question and awaiting the answer...
Good luck!
Maybe it's because the image never send to server via ajax, so $_FILES have nothing under 'image' index.
Take a look at how to do file upload using jquery serialization
or consider to use FormData object.
Change <input name="image" type="file" id="inputImage"/ to <input name="image" type="file" id="inputImage"/>

Categories