Query is If I select 'Select a New Parent category' from dropdown, a new textbox gets appear. I wants to insert that value into database. That textbox is hidden bydefault.
HTML FILE
<head>
<script type="text/javascript">
$(document).ready(function() {
$('#parentcat').change(function(){
if($('#parentcat').val() === 'Create a New Parent Category')
{
$('#other').show();
$('#catname').hide();
}
else
{
$('#other').hide();
$('#catname').show();
}
});
});
</script> </head>
<table>
<body>
<form method="POST" action="" name="form1" enctype="multipart/form-data" >
<tr>
<td><h4>Add category</h4></td>
</tr>
<tr>
<td>Select parent Category:</td><td><select name="parentcat" id="parentcat">
<?php
include "../storescripts/connect_to_mysql.php";
$result=mysql_query("SELECT parent from category"); while($row=mysql_fetch_array($result)){
echo "<option>".$row['parent'];"</option>";
} ?>
<option value="Create a New Parent Category">Create a New Parent Category</option>
</select><br/></td>
<tr><td><input type="text" id="other" name="other" placeholder="New Parent Category Name:" style="display: none;"/></td></tr>
</tr>
<tr>
<td></td><td><input type="text" name="catname" placeholder="SubCategory name" id="catname"><br/></td>
</tr>
<tr>
<td>Status:
</td>
<td><select name="status" >
<option selected="Active">Active</option>
<option>Inactive</option>
</select></td>
</tr>
<tr><td>Category Image :</td><td><input type="file" name="imageUpload" id="imageUpload"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submit" value="Insert"></td>
</tr>
</form>
</table>
Here is my complete HTML file,bydefault 'other' dropdown is hidden. Now Here I'm providing my php code that inserts values into database, issue is how can I insert value of hidden filed into database. My database fields includes : cat_id(Auto-increment),cat_name,parent,cat_status,cat_image.
Here Is my php code for inserting values into database.
<?php
if(isset($_POST['submit']))
{
$parentcat=$_POST['parentcat'];
$catname=$_POST['catname'];
$status=$_POST['status'];
$target_dir = "../uploads/";
$target_file = $target_dir . basename($_FILES["imageUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if (move_uploaded_file($_FILES["imageUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["imageUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
$image=basename( $_FILES["imageUpload"]["name"],".jpg"); // used to store the filename in a variable
$sql = mysql_query("SELECT cat_id FROM category WHERE cat_name='$catname' LIMIT 1");
$CatMatch = mysql_num_rows($sql); // count the output amount
if ($CatMatch > 0) {
echo 'Sorry you tried to place a duplicate "Category Name" into the system, click here';
exit();
}
else{
$sql=mysql_query("INSERT INTO `category` (`cat_name`, `parent`, `cat_status`,`cat_image`) VALUES ('$catname', '$parentcat', '$status','$image') ");
echo $sql;
}
}
?>
For an eg. If I Select A new parent category then Subcategory named textbox appears and I want to insert that value into database. How Can i do that.
Change your jquery code like this
<script type="text/javascript">
$(document).ready(function () {
$('#parentcat').change(function () {
if ($('#parentcat').val() === 'Create a New Parent Category'){
$('#other').prop('type', 'text');
$('#catname').prop('type', 'hidden');
}
else{
$('#other').prop('type', 'hidden');
$('#catname').prop('type', 'text');
}
});
});
</script>
Also change your HTML code for #other input box like this
<input type="hidden" id="other" name="other" placeholder="New Parent Category Name:"/>
Let me know if it works for you.
Edit
In your PHP file, Instead of $catname=$_POST['catname']; add this
$catname = ( $parentcat == "Create a New Parent Category") ? $_POST['other'] : $_POST['catname'];
Related
This question already has answers here:
What does enctype='multipart/form-data' mean?
(9 answers)
Closed 6 years ago.
I have a simple registration form, in which I accept inputs from the user that includes an image, and insert the values in a table : temporary_employees table . In my code, I check whether the email id and the user id entered by the user already exists and if they dont , i go ahead and perform the insert after moving the image to a folder named 'images' . While running the code , I am getting an error Undefined index: image, on the line where I have the following piece of code :
$target_file = $target_path . basename ($_FILES['image']['name']);
The most interesting thing is the same line of code has worked perfectly well in another php file . I had given the same name for the input in the html form . . How is it possible ? Any help will be appreciated .
Here is my code :
//start the session before anything is echoed to the browser
if (session_status()===PHP_SESSION_NONE) {
session_start();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>
Login form
</title>
</head>
<body>
<h3>Registration Form</h3>
<form action ="" method="POST">
<table align="center" cellpadding="10">
<tr>
<td>Name</td>
<td><input type="text" maxlength='100' name="empname" id="empname" required></td>
</tr>
<tr>
<td>Email Id</td>
<td><input type="text" maxlength='100' name="emailid" id="emailid" required>
</td>
</tr>
<tr>
<td>User Id</td>
<td><input type="text" maxlength='100' name="userid" id="userid" required ></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" maxlength='100' name="pwd" id="pwd" required ></td>
</tr>
<tr>
<td>Date of Birth</td>
<td>
<select name='year'>
<option value='2015'>2015</option>
<option value='2016'>2016</option>
</select>
<select name='month'>
<option value='01'>January</option>
<option value='02'>February</option>
<option value='03'>March</option>
<option value='04'>April</option>
<option value='05'>May</option>
</select>
<select name='day'>
<option value='01'>1</option>
<option value='02'>2</option>
<option value='03'>3</option>
<option value='04'>4</option>
<option value='05'>5</option>
</select></td>
</tr>
<tr>
<td>Designation</td>
<td><input type="text" maxlength='100' name="designation" id="designation" required></td>
</tr>
<tr>
<td>Department</td>
<td><input type="text" maxlength='100' name="department" id="department" required></td>
</tr>
<tr>
<td>Image</td>
<td><input type="file" maxlength='100' name="image" required></td>
</tr>
<tr>
<td>
<input type="submit" name="login" value="Register Yourself">
</td>
</tr>
</table>
</form>
</body>
</html>
<?php
//create a connection
$conn = mysqli_connect('localhost', 'root', '', 'attendance');
//on the click of submit button
if (isset($_POST['login'])) {
//capture the $_POST values
$name = $_POST['empname'];
$name = trim($name);
$email = $_POST['emailid'];
$email = trim($email);
$userid = $_POST['userid'];
$userid = trim($userid);
$pwd = $_POST['pwd'];
$pwd = trim($pwd);
$desg = $_POST['designation'];
$desg = trim($desg);
$dept = $_POST['department'];
$dept = trim($dept);
$day = $_POST['day'];
$month = $_POST['month'];
$year = $_POST['year'];
$date = $year.$month.$day;
//display a message if there is a blank entry for email
if ($email=="") {
echo "Please enter a valid email id";
}
//display a message if there is a blank entry for userid
if ($userid=="") {
echo "Please enter a valid User Id";
}
//check if the email id exists
$sql_check_email = "select * from employee where emp_email='$email';";
mysqli_query($conn, $sql_check_email);
$aff_email = mysqli_affected_rows($conn);
// if email id exists ..display message
if ($aff_email==1) {
$msgemail = "The email id exists";
echo $msgemail;
//display error message if there is an error
} else if ($aff_email>1) {
$msgemail = "There are multiple employees with the same email";
echo $msgemail;
//display message if there is an error firing the query
} else if ($aff_email<0) {
echo "There is an error ..Try again";
}
//check if the user id exists
$sql_check_userid = "select * from employee_login where emp_uid='$userid';";
mysqli_query($conn, $sql_check_userid);
$aff_userid = mysqli_affected_rows($conn);
if ($aff_userid==1) {
$umsg = "User id already exist";
echo $umsg;
//display error message if there is an error when the query is fired
} else if ($aff_userid<0) {
echo "There is an error ..Try again";
}
//if neither the user id nor the email id exist, upload image and do the insert
if ($aff_userid==0 && $aff_email==0) {
$target_path = "images/";
$target_file = $target_path . basename ($_FILES['image']['name']);
//if the image is moved to the images folder , do the insert
if (move_uploaded_file($_FILES['image']['tmp_name'], $target_file)) {
$image = basename($_FILES['image']['name']);
$sql_ins = "INSERT INTO temporary_employee(emp_uid,emp_pwd,
emp_name,emp_email,emp_dob,emp_designation,
emp_department,emp_image)
VALUES('$userid','$pwd','$name','$email','$date',
'$desg','$dept','$image')";
mysqli_query($conn, $sql_ins);
$aff_insert = mysqli_affected_rows($conn);
//display success message if insert is successfull
if ($aff_insert==1) {
echo "You have successfully registered ...awaiting approval by admin";
//display message if there were no insert
} else if ($aff_insert==0) {
echo "The registration has failed ..Try again";
//diplay error message if there was an error while firing the insert query
} else if ($aff_insert<0) {
echo "There was an error ..Try again";
}
}
}
}
?>
While using Image Uploading in the form you have to use the enctype in the form attribute.
<form action ="" method="POST" enctype="multipart/form-data">
</form>
Change
<form action ="" method="POST">
to
<form enctype="multipart/form-data">
And try again.
The enctype attribute specifies how the form-data should be encoded when submitting it to the server.
Here is my code for insertion product. Everything is working fine with db, but the image column stays empty whenever I insert an image /choose file. It also does not have any effect or error when the image is not chosen, but if I do not choose any other field, the table in db stays empty. Its opposite in the case of an image. I've found tutorials on image uploading but they are not working wd my code as well. Any suggestions?
<?php
include 'includes/overall/head.php';
include 'core/init.php';
?>
<script src="//tinymce.cachefly.net/4.2/tinymce.min.js"></script>
<script>tinymce.init({selector:'textarea'});</script>
<?php
include 'includes/aside.php';
?>
<div class="container-form">
<div align="center">
<h1>Insert Products</h1>
</div>
<!--Register users here-->
<div class=>
<form action="insert_product.php" method="post" enctype="multipart/form_data">
<div class="table-responsive">
<table class="table" width="700" align="center" border="1">
<tr>
<td><strong>Car Title</strong></td>
<td><input type="text" name= "product_title"></td>
</tr>
<tr>
<td><strong>Car Category</strong></td>
<td>
<select name="product_cat">
<option>Select Category</option>
<?php
// SQL query
$strSQL = "SELECT * FROM categories ";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Loop the recordset $rs
while($row = mysql_fetch_array($rs)) {
// Name of the person
$cat_id = $row['cat_id'] ;
$cat_title = $row['cat_title'] ;
// Create a link to person.php with the id-value in the URL
$strLink = "<a href = 'person.php?id = " . $row['cat_id'] . "'</a>";
// List link
echo "<option value='$cat_id'>$cat_title</option>";
//echo "<li>" . $btitle . "</li>";
}
?>
</select>
</td>
</tr>
<tr>
<td><strong>Car Company</strong></td>
<td>
<select name="product_brand">
<option>Select Company</option>
<?php
// SQL query
$brand = "SELECT * FROM brands ";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($brand);
// Loop the recordset $rs
while($row = mysql_fetch_array($rs)) {
// Name of the person
$brand_id = $row['brand_id'] ;
$brand_title = $row['brand_title'] ;
// Create a link to person.php with the id-value in the URL
$strLink = "<a href = 'person.php?id = " . $row['brand_id'] . "'</a>";
// List link
echo "<option value='$brand_id'>$brand_title</option>";
//echo "<li>" . $btitle . "</li>";
}
?>
</select>
</td>
</tr>
<tr>
<td><strong>Add Image</strong></td>
<td>
<input name="MAX_FILE_SIZE" value="102400" type="hidden">
<input name="image" accept="image/jpeg" type="file">
</td>
</tr>
<tr>
<td><strong>Car Rent</strong></td>
<td><input type="text" name= "product_price"></td>
</tr>
<tr>
<td><strong>Car Description</strong></td>
<td><textarea name="product_description"></textarea></td>
</tr>
<tr>
<td><strong>Car Keyword</strong></td>
<td><input type="text" name= "product_keywords"></td>
</tr>
<td colspan="2">
<button type="submit" name="insert_product" class="btn btn-primary col-md-offset-6">Add Vehicle</button>
</td>
</table>
</div>
</form>
<div>
</div>
</div>
</div>
<?php
if(isset($_POST['insert_product'])){
//text data variables
$product_title=$_POST['product_title'];
$product_cat=$_POST['product_cat'];
$product_brand=$_POST['product_brand'];
$product_price=$_POST['product_price'];
$product_description=$_POST['product_description'];
$product_status='on';
$product_keywords=$_POST['product_keywords'];
//image names: media file or multipart data
$image=isset($_FILES['image']['name']);
//Temp names
$temp_name1=isset($_FILES['image']['temp_name']);
//validation:
if($product_title=='' OR $product_cat=='' OR $product_brand=='' OR $product_price==''OR $product_keywords==''
OR $product_description=='' OR $image='') {
echo "<script>alert('Please fill all the fields')</script>";
exit();
}
//here is my upload image to folder code but its not working
//upload images to folder
move_uploaded_file($temp_name1 , "product_images/$image");
$query= "INSERT INTO product ( cat_id, brand_id, date, product_title, image, product_price, product_description, product_status)
VALUES ( '$product_cat' , '$product_brand' , NOW() , '$product_title' , '$image' , '$product_price' , '$product_description' , '$product_status')";
$rs = mysql_query($query);
// Loop the recordset $rs
if($rs) {
echo 'Successful';
}
}
?>
<!-------------------------------------------------------->
<?php
include 'includes/footer.php';
?>
You have serveral errors in the query. First you forgot to add dots between de variables.
$query= "INSERT INTO product ( cat_id, brand_id, date, product_title, image, product_price, product_description, product_status)
VALUES ( '.$product_cat.' , '.$product_brand.' , NOW() , '.$product_title.' , '.$image.' , '.$product_price.' , '.$product_description.' , '.$product_status.')";
Also you miss a space before the OR between $product_price and $product_keywords
OR $product_brand=='' OR $product_price==''OR $product_keywords==''
And make sure that the connection with your database is set correctly
EDIT:
The first part is wrong. You dont need to add dots. Otherwise the dots will be displayed in the database. Sorry for the misunderstanding
<div id="home">
<div class="container">
<form action="" method="post">
<b><font color = "000099"><select name="category" id="category">
<option>Name </option>
<option>Email</option>
<option>Employee</option>
<option>Customer</option>
</select></font></b>
<b><font color = "000099"><select name="read" id="read">
<option>New</option>
<option>Archive</option>
</select></b>
<font color = "339933"><b><input name="value" type="text" placeholder="Value" /> </b>
<input type="submit" value="GO"/></font><br>
</form>
<font color = "339933"><b>
</b></font>
<p><div id="body">
<table width="98%" border="1">
<tr></tr>
<tr>
<td><font color = "339933"><b>Name</td>
<td><font color = "339933"><b>E-Mail </td>
<td><font color = "339933"><b>Access</td>
<td><font color = "339933"><b>Update </td>
</tr>
<?php
$read = $_POST['read'];
If($read == 'New'){
$read = '0';
}
If($read == 'Archive'){
$read = '1';
$arc = 'AND date < CURDATE() - INTERVAL 90 DAY';
}
$category = $_POST['category'];
$value = $_POST['value'];
if($category == 'Name'){
$where = " where name like '%$value%' ";
}else if($category == 'E-mail'){
$where = " where Email like '%$value%' ";
}else if($category == 'Employee'){
$where = " where Email like '%$value%' ";
}else if($category == 'Customer'){
$where = " where Email not like '%$value%' ";
}
$select = 'SELECT *';
$from = ' FROM users';
if($where == ''){
$where = ' WHERE TRUE ';
}
$order = " order by id desc limit 100";
if($read == '0'){
$sql = $select . $from . $where . $order ;
}else{
$sql = $select . $from . $where . $arc . $order ;
}
$result_set=mysql_query($sql);
while($row=mysql_fetch_array($result_set)) {
?>
<tr>
<form method="post" name="forms" action="">
<td><font color = Black><?php echo $row['name']; ?></td>
<td><div id= "remail" name="remail"><font color = Black><?php echo $row['Email']; ?></div></td>
<td><input type="text" name="access_rights" class="form-control" value="<?php echo $row['access']; ?>" required="required" ></td>
<td><input type="submit" class="submit_button" id="submit_button" name="submit_button" value="Update"/></td>
</form>
<?php } ?>
</table>
</div>
</body>
<script type="text/javascript">
$(function() {
$(".submit_button").click(function() {
alert('asfsfsds');
var ID = $(this).attr("id");
var dataString1 = 'msg_id='+ ID;
var mail = $("#remail").val();
var mailid = 'remail='+ mail;
var textcontent = $("#access_rights").val();
var dataString = 'access_rights='+ textcontent;
if(textcontent==''){
alert("Enter some Value..");
$("#access_rights").focus();
} else {
$.ajax({
type: "POST",
url: "action.php",
data: dataString,mailid,dataString1,
cache: true,
success: function(html){
document.getElementById('access_rights').value='';
$("#access_rights").focus();
}
});
}
return false;
});
});
</script>
</html>
Above is my php ajax code. I want to one field in mysql database by ajax.
There are multiple submit button on the page. Let me explain you properly.
Below code is used for sorting the value on the page. This value retrieve from database. This is working fine. I can get the data from database and it is showing in the same page.
<form action="" method="post">
<b><font color = "000099">
<select name="category" id="category">
<option>Name </option>
<option>Email</option>
<option>Employee</option>
<option>Customer</option>
</select>
</font></b>
<b><font color = "000099">
<select name="read" id="read">
<option>New</option>
<option>Archive</option>
</select>
</b>
<font color = "339933"><b><input name="value" type="text" placeholder="Value" /></b>
<input type="submit" value="GO"/></font><br>
</form>
In below code data is showing from database and one text box and submit button will display in table.
<form method="post" name="forms" action="">
<tr>
<td><font color = Black><?php echo $row['name']; ?></td>
<td><div id= "remail" name="remail"><font color = Black><?php echo $row['Email']; ?></div></td>
<td><input type="text" name="access_rights" class="form-control" value="<?php echo $row['access'];?>" required="required" ></td>
<td><input type="submit" class="submit_button" id="submit_button" name="submit_button" value="Update"/></td>
</tr>
</form>
I want user with special permission can update the value by ajax because there could be multiple rows and it is not good to page get refreshed each time.
At the moment after clicking on update button ajax event not firing.
Can anybody advise me on this. I am not good in ajax.
There may be other issues, but the following line is syntactically incorrect:
data: dataString,mailid,dataString1,
That is not how you concatenate a string in Javascript. Plus, you would need to separate the name=value pairs with ampersands.
Instead of concatenating a string, you can use an object and let JQuery do the concatenating:
data: {
'access_rights': $("#access_rights").val(),
'remail': $("#remail").val(),
'msg_id': $(this).attr("id")
},
UPDATE:
You don't have an element with id="access_rights. You do have an element with id="remail", but you create that element in a loop, so you will have multiple elements with that id.
You need to get the values of the elements that are in the same row as the clicked submit button. You can't do that using id values. Instead, you use .closest('tr') on the button element to get the surrounding row. You can then use .find() on the row element to get the values in that row.
Change:
<td><div id= "remail" name="remail"><font color = Black><?php echo $row['Email']; ?></div></td>
To:
<td><font color="Black" class="remail"><?php echo $row['Email']; ?></td>
Then you can have:
$(".submit_button").click(function() {
var $submitBtn = $(this),
$row = $(this).closest('tr'),
$accessRights = $row.find("input[name=access_rights]"),
accessRights = $accessRights.val();
if (accessRights == ''){
alert("Enter some Value..");
$accessRights.focus();
} else {
$.ajax({
type: "POST",
url: "action.php",
data: {
'access_rights': accessRights,
'remail': $row.find(".remail").text(),
'msg_id': $submitBtn.attr("id")
},
cache: true,
success: function(html){
$accessRights.val('').focus();
}
});
}
return false;
});
You are also missing the closing </tr> tag.
I'm relatively new to PHP and need some help checking to see 1. If an image has been uploaded for submission and complete one set of submission ELSE IF an image has not been uploaded, submit a different set of sql information.
I've previously tried isset(), is_uploaded_file(), and file_exists(), and cannot seem to get anything to send.
HTML FORM
<form method="POST" action="php/editInv.php" enctype="multipart/form-data" id="editInv">
<table>
<tbody>
<?php
$productId = $_GET['productId'];
require ('php/dbcon.php');
$con=mysqli_connect(HOST,USER,PASS,DB);
$sqlId = "SELECT * FROM products WHERE productId='".$productId."'";
$sqlIdResult = mysqli_query($con,$sqlId);
while($rowId=mysqli_fetch_array($sqlIdResult)) {
?>
<tr>
<td>
<label for="productName">Product Name: </label>
</td>
<td>
<input name="productName" id="productName" type="text" value="<?php echo $rowId['productName']; ?>"/>
<input name="prodId" id="prodId" type="hidden" value="<?php echo $rowId['productId']; ?>" />
</td>
<td>
<label for="productDesc">Product Description: </label>
</td>
<td rowspan="4">
<textarea name="productDesc" id="productDesc" cols="55" rows="10"><?php echo $rowId['productDesc']; ?></textarea>
</td>
</tr>
<tr>
<td>
<label for="gender">Gender: </label>
</td>
<td>
<select name="gender" id="gender">
<option id="1" value="1">Male</option>
<option id="2" value="2">Female</option>
<option id="3" value="3">Unisex</option>
</select>
<input type="hidden" value="<?php echo $rowId['genderId']; ?>" id="genderHid"/>
<script>
var gender=$('#genderHid').val();
var selected=$('#gender').find('#'+gender);
$(selected).attr('selected','selected');
</script>
</td>
</tr>
<tr>
<td>
<label for="inventory">Inventory: </label>
</td>
<td>
<input type="number" name="inventory" id="inventory" value="<?php echo $rowId['inventory']; ?>"/>
</td>
</tr>
<tr>
<td>
<label for="price">Price: </label>
</td>
<td>
$<input type="text" name="price" id="price" value="<?php echo $rowId['price']; ?>" />
</td>
</tr>
<tr>
<td>
<label for="productImage">Upload Image: </label>
</td>
<td>
<input type="file" name="productImage" id="productImage" />
</td>
<td colspan="2">
<div id="progress" style="width:100%;">
<div id="bar" style="height:50px;background-color:blue;width:0%;">
</div>
<p id="percent"></p>
</div>
</td>
</tr>
<tr>
<td colspan="2" rowspan="2">
<img id="prevImage" style="" src="<?php echo $rowId['productImage']; ?>" />
</td>
<td id="response">
</td>
<td>
<button type="submit" id="editInv">Edit Item</button>
</td>
</tr>
<tr>
</tr>
<?php
};
?>
</tbody>
</table>
</form>
AJAX
var options = {
beforeSubmit: function() {
// pre submit callback
$("#progress").show();
$("#percent").html("0%");
},
data: {
productName : $('#productName').val(),
productDesc : $('#productDesc').val(),
inventory : $('#inventory').val(),
price : $('#price').val(),
gender : $('#gender').val(),
image : $('#prevImage').attr('src'),
prodId : $('#prodId').val()
},
uploadProgress: function(event, position, total, percentComplete) {
//during submission
$("#bar").width(percentComplete+'%');
$("#percent").html(percentComplete+'%');
},
success: function(msg) {
//post submit call back
$(".bar").css("width","100%");
$(".percent").html('100%');
$("#response").html(response.responseText);
},
complete: function(response) {
if(response.responseText=="Invalid File"){
} else {
$("#response").html(response.responseText);
//$("#addNew")[0].reset();
//$("#prevImage").attr('src','').hide();
$(".bar").css("width","0%");
$(".percent").html('0%');
}
},
error: function(response) {
alert(response.responseText);
}
};
$("#editInv").ajaxForm(options);
PHP
//If a file has been uploaded
if (!empty($_FILES["productImage"]["name"])) {
$target_dir = $_SERVER['DOCUMENT_ROOT'] . "/images/inventory/";
$target_file = $target_dir . basename($_FILES["productImage"]["name"]);
$fileName = str_replace(' ', '', $productName);
$target_file_insert = "/images/inventory/" . $fileName . ".jpg";
$targetFileUpload = $target_dir . $fileName . ".jpg";
$sql1 = "UPDATE products SET productName='".$productName."', productDesc='".$productDesc."', inventory='".$inventory."', price='".$price."', genderId='".$gender."', productImage='".$targetFileUpload."' WHERE productId='".$prodId."'";
mysqli_query($con,$sql1);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["productImage"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "jpeg" && $imageFileType != "JPG" && $imageFileType != "JPEG") {
echo "Sorry, only JPG, and JPEG files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["productImage"]["tmp_name"], $targetFileUpload)) {
mysqli_close($con);
} else {
echo "Sorry, there was an error uploading your file.";
}
}
} else
//If a file has not been uploaded
/*if (empty($_FILES["productImage"]["name"])) */{
$sql2="UPDATE products SET productName='".$productName."', productDesc='".$productDesc."', inventory='".$inventory."', price='".$price."', genderId='".$gender."', productImage='".$image."' WHERE productId='".$prodId."'";
mysqli_query($con,$sql2);
}
The path you need to check is $targetFileUpload not $upload.
Once uploaded check:
if (!file_exists($targetFileUpload)){...}
Ok, it was actually being caused by two different issues, one in the PHP and one in the order in which the variables were called in the JavaScript. I had to call everything except for the generated image using jQuery at the top of the page as global variables, then put the jQuery AJAX at the bottom of the page with the form action call.
Apparently, using the jQuery to call the values of the fields at the bottom of the page caused them to send the information that the page populated with from the back end, while placing them at the top of the page causes them to relay the changed input data to the AJAX call.
Any explinations why this worked this way?
<script>
var productName = $('#productName').val();
var productDesc = $('#productDesc').val();
var inventory = $('#inventory').val();
var price = $('#price').val();
var gender = $('#gender').val();
var prodId = $('#prodId').val();
</script>
//All your HTML Content
<script>
var options = {
beforeSubmit: function() {
// pre submit callback
$("#progress").show();
$("#percent").html("0%");
},
data: {
productName : productName,
productDesc : productDesc,
inventory : inventory,
price : price,
gender : gender,
image : $('#prevImage').attr('src'),
prodId : prodId
},
uploadProgress: function(event, position, total, percentComplete) {
//during submission
$("#bar").width(percentComplete+'%');
$("#percent").html(percentComplete+'%');
},
success: function(msg) {
//post submit call back
$(".bar").css("width","100%");
$(".percent").html('100%');
$("#response").html(response.responseText);
},
complete: function(response) {
if(response.responseText=="Invalid File"){
} else {
$("#response").html(response.responseText);
//$("#addNew")[0].reset();
//$("#prevImage").attr('src','').hide();
$(".bar").css("width","0%");
$(".percent").html('0%');
}
},
error: function(response) {
alert(response.responseText);
}
};
$("#editInv").ajaxForm(options);
</script>
PHP if statement statement essentially looks like this:
if (!empty($_FILES["productImage"]["name"])) {
} else
//If a file has not been uploaded
if (empty($_FILES["productImage"]["name"])) {
}
Thank you #fred-ii- for the error catcher.
I have been trying the whole week to get this too work but haven't had any luck thus far. I am building an employee system, being my first project I could really use your help.
I have a database with a table called ref_employees with x amount of fields.
I managed to get my hands on some source to edit the record and thought that my problem was solved. Although the source helped me to edit the records, the client needs more functionality by means of upload and storing functionality. I have edited the code accordingly but have 2 issues now.
1) I had to add the upload form separate to the editing form because when the edits' update is clicked it clears the upload fields within the db even after adding echoing out the current values within the upload fields in the db.
2) The uploads shows that it is uploading but is doesn't get saved in the specified directory. The permissions are set to 777, and the file names are not captured in the database in the relevant fields. I think it is because the upload function is in a separate page and not on the same page as the upload form.
I need it to upload the file, store it in a directory and finally place the file name in the db where the warning fields are, but it needs to be captured under the record (employee) being edited.
I am new to this and all help is appreciated.
The edit page:
<?php
include 'core/init.php';
protect_page();
include 'includes/overall/header.php';
error_reporting(1);
?>
<?php
/*
EDIT.PHP
Allows user to edit specific entry in database
*/
// creates the edit record form
// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($idnumber, $firstname, $lastname, $department, $manager, $startdate, $error)
{
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Edit Record</title>
</head>
<body>
<div class="article">
<h1>Employee Details</h1>
<?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" enctype="multipart/form-data">
<input type="hidden" name="idnumber" value="<?php echo $idnumber; ?>"/>
<div>
<p>* Required</p>
<p><strong>ID:</strong> <?php echo $idnumber; ?></p>
<table cellpadding="5" cellspacing="5">
<tr>
<td><strong>First Name: *</strong></td>
<td><input type="text" name="firstname" value="<?php echo $firstname; ?>"/></td>
</tr>
<tr>
<td><strong>Last Name: *</strong></td>
<td> <input type="text" name="lastname" value="<?php echo $lastname; ?>"/></td>
</tr>
<tr>
<td><strong>Department: *</strong> </td>
<td> <input type="text" name="department" value="<?php echo $department; ?>"/></td>
</tr>
<tr>
<td><strong>Manager/Superviser: *</strong></td>
<td><input type="text" name="manager" value="<?php echo $manager; ?>"/></td>
</tr>
<tr>
<td><strong>Start Date: *</strong></td>
<td><input type="text" name="startdate" value="<?php echo $startdate; ?>"/></td>
</tr>
<tr>
<td><input type="submit" name="submit" value="Submit" class="btn"></td>
</tr>
</table>
</form>
<tr>
<td>
<table cellpadding="5" cellspacing="0">
<form action="includes/add.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="idnumber" value="<?php echo $idnumber; ?>"/>
<th>Ad Warnings Documents</th>
<tr>
<td>Warning File 1</td>
<td><input type="file" name="warning1" value="<?php echo $warning1;?>" /></td>
</tr>
<tr>
<td>Warning File 2</td>
<td><input type="file" name="warning2" value="<?php echo $warning2;?>" /></td>
</tr>
<tr>
<td>Warning File 3</td>
<td><input type="file" name="warning3" value="<?php echo $warning3;?>" /></td>
</tr>
<tr><td><input type="submit" name="submit" value="upload"></td></tr>
</table>
</td>
<td></td>
</tr>
</table>
</div>
</body>
</html>
<?php
}
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// confirm that the 'id' value is a valid integer before getting the form data
if (is_numeric($_POST['idnumber']))
{
// get form data, making sure it is valid
$idnumber = $_POST['idnumber'];
$firstname = mysql_real_escape_string(htmlspecialchars($_POST['firstname']));
$lastname = mysql_real_escape_string(htmlspecialchars($_POST['lastname']));
$department = mysql_real_escape_string(htmlspecialchars($_POST['department']));
$manager = mysql_real_escape_string(htmlspecialchars($_POST['manager']));
$startdate = mysql_real_escape_string(htmlspecialchars($_POST['startdate']));
// check that firstname/lastname fields are both filled in
if ($firstname == '' || $lastname == '')
{
// generate error message
$error = 'ERROR: Please fill in all fields!';
//error, display form
renderForm($idnumber, $firstname, $lastname, $department, $manager, $startdate, $error);
}
else
{
// save the data to the database
mysql_query("UPDATE ref_employees SET firstname='$firstname', lastname='$lastname', department='$department', manager='$manager', startdate='$startdate' WHERE idnumber='$idnumber'")
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: employeelist.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['idnumber']) && is_numeric($_GET['idnumber']) && $_GET['idnumber'] > 0)
{
// query db
$idnumber = $_GET['idnumber'];
$result = mysql_query("SELECT * FROM ref_employees WHERE idnumber=$idnumber")
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
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$department = $row['department'];
$manager = $row['manager'];
$startdate = $row['startdate'];
$warning1 = $row['warning1'];
$warning2 = $row['warning2'];
$warning3 = $row['warning3'];
// show form
renderForm($idnumber, $firstname, $lastname, $department, $manager, $startdate, '');
}
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!';
}
}
?>
<h1>Additional options</h1>
</div>
The file upload source file add.php
<?php
include 'core/init.php';
protect_page();
include 'includes/overall/header.php';
error_reporting(1);
?>
<?php
//This is the directory where images will be saved
$target = "files/empdocs";
$target1 = $target . basename( $_FILES['warning1']['name']);
$target2 = $target . basename( $_FILES['warning2']['name']);
$target3 = $target . basename( $_FILES['warning3']['name']);
//This gets all the other information from the form
$warning1=($_FILES['warning1']['name']);
$warning2=($_FILES['warning2']['name']);
$warning3=($_FILES['warning3']['name']);
//Writes the information to the database
mysql_query("INSERT INTO ref_employees VALUES ('$warning1', '$warning2', '$warning3')") ;
//Writes the file to the server
if (move_uploaded_file($_FILES['warning1']['tmp_name'], $target1)
&& move_uploaded_file($_FILES['warning2']['tmp_name'], $target2)
&& move_uploaded_file($_FILES['warning3']['tmp_name'], $target3)) {
//Tells you if its all ok
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory";
}
else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?>