Set column as empty if no file is selected when submit - php

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>";
}
}

Related

why <input = "file"> on modal can't pass image to php

I'm rookie at php and html, i have this modal that has in it which i need for inserting an image..
if (isset($_POST['add_roomtype_action'])) {
require 'script/addRoomType.php';
}
<div class="modal fade" id="add_roomtype_modal" tabindex="-1" role="dialog"
aria-labelledby="add_roomtype_modal" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-
hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Add Room Type</h4>
</div>
<form action="room_management.php" method="post"
autocomplete="off">
<div class="modal-body">
<input type="hidden" id="upd_roomtype_id" name =
"add_roomtype_idnm">
<label style="font-size: 10pt">Room Type : </label>
<input type="text" id="add_roomtype" name = "add_roomtypenm"
style="font-size: 10pt" ><br></br>
<label style="font-size: 10pt">Rate : </label>
<input type="text" id="addupd_rate" name = "add_ratenm"
style="font-size: 10pt" ><br></br>
<label style="font-size: 10pt">Image : </label>
<input type="file" id ="add_roomtypeImgid"
name="add_roomtypeImgnm" accept="image/x-png,image/jpeg">
</div>
<div class="modal-footer">
<button type="button" class="btn" data-
dismiss="modal">Close</button>
<button type="submit" class="btn" id = "add_roomtype_action"
name = "add_roomtype_action">Add</button>
</div>
</form>
</div>
</div>
</div>
and this is the php file which the modal will call
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "afgroms";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['add_roomtype_action'])){
$roomtypeid = $_POST['add_roomtype_idnm'];
$roomtype = $_POST['add_roomtypenm'];
$rate = $_POST['add_ratenm'];
$file = $_FILES['add_roomtypeImgnm'];
$fileName = $file['name'];
$fileTmpName = $file['tmp_name'];
$fileSize = $file['size'];
$fileError = $file['error'];
$fileType = $file['type'];
$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('jpg','jpeg','png');
if(in_array($fileActualExt, $allowed)){
if($fileError === 0)
{
if ($fileSize > 500000) {
mysql_query("UPDATE `tbl_roomtype` SET `RoomType` =
'$roomtype', `Rate` = '$rate', `Image` = '$img' WHERE RoomTypeID =
".$roomtypeid);
echo "<script>";
echo "alert(\"Successfully Added!\");";
echo "</script>";
}else{
echo "<script>";
echo "alert(\"File size too big!\");";
echo "</script>";
}
}else
{
echo "<script>";
echo "alert(\"There was an error\");";
echo "</script>";
}
}else
{
echo "<script>";
echo "alert(\"You cannot upload this type of file\");";
echo "</script>";
}
}
?>
but this error keep on occurring : Notice: Undefined index: add_roomtypeImgnm...
help me out here guys, i don't know whats the problem. I already tried to change the name and id of my and same error keeps on occurring.
The reason why you cannot post files is not your modal dialog but the fact that you are not using enctype="multipart/form-data" in your form.
Try it like this and it should work.

Can't upload file in BLOB to the database, Directory issues in PHP

I'm having difficulties to insert the value as blob type always empty and the other method can't insert the images in a folder. Please you can show the way out. Thanks! This code is to save the image in a folder and then access it with the name to display, but is not saving the photos to the folder. I edited and include the form here, containing JavaScript and css .It looks some how messy but i'm a beginner. Thanks.
<?php
include("../views/post_form.php");
require("../includes/include.php");
require("../includes/sess_n.php");
if ($_SERVER["REQUEST_METHOD"]== "POST")
{
$usertext = $_POST["usertext"];
$image = $_FILES['image']['name'];
$talent =$_POST["talenttype"];
if(empty($usertext) || empty($image)|| empty($talent))
{
die();
}
$id = $_SESSION["id"];
$folder ="images/".basename($_FILES['image']['name']);
move_uploaded_file($_FILES['image']['tmp_name'],$folder) ;
$query = mysqli_query($link,"SELECT * FROM `upload` WHERE id = '$id'");
$upload = mysqli_query($link,"INSERT INTO `upload` (description,image,talent,folder) VALUES('$usertext','$image','$talent','$folder ')");
}
?>
To display, I want the photos to be save to the folder, not saving. I used blob method not inserting into the database.
<?php
include("../views/feeds_form.php");
require("../includes/include.php");
require("../includes/sess_n.php");
$query = mysqli_query($link,"SELECT * FROM `upload` ");
if ($query === false)
{
die();
}
echo '<table>';
while ($run = mysqli_fetch_assoc($query))
{
echo '<tr>';
echo '<td>';?> <img src =" <?php echo $run["image"]; ?>" height=100 width=100> <?php echo '<td>';
echo '<td>'; echo $run["description"]; echo '<td>'; echo $run["folder"];echo '<td>';
echo '</tr>';
}
echo '</table>';
?>
The form here.
<?php
include("../public/header.php");
?>
<div><title>post</title></div>
<style>
.form-inline
{
text-align: center;
margin-bottom: 50px;
}
</style>
<script type="text/javascript">
function validate(){
var usertext = document.getElementById("usertext");
var talent = document.getElementById("talenttype");
var image = document.getElementById("image");
if (usertext.value === "" && talent.value === "" && image.value ==="")
{
alert("Field Must Not be Empty");
}
}
</script>
<form class="form-inline" method ="POST" action ="post.php" enctype="multipart/form-data" onsubmit= "return validate();">
<div class="form-group">
<label class="sr-only" for="exampleInputEmail3"> </label>
<textarea class="form-control" id = "usertext" name ="usertext" rows="5" placeholder="Describe Person Here"></textarea> <br><hr>
<label class="sr-only" for="exampleInputEmail3"></label><br>
<div class="form-group">
<label for="exampleInputPassword1"></label>
<input type="file" class="form-control" id = "image" id="exampleInputPassword1" name="image" placeholder="image">
</div> <br><br><br> <hr>
<div class="form-group">
<label for="exampleInputPassword1"></label>
<input type="text" class="form-control" id = "talenttype" id="exampleInputPassword1" name = "talenttype" placeholder="Talent-Type"><br><br>
</div> <hr>
<div>
<button type="submit" name ="post" class="btn btn-default">Post</button><br>
</div>
</div>
</form>
<?php
include("../public/footer.php");
?>
I was having permission issues, the images folder permission was changed. That solves everything. Thanks!

The Uploaded Image doesn't Save on the database

I'am having a button to upload a image and Every time I upload an Image the images doesn't saves on the database and there is no error given,
Here is my Code:
<td>
<form method="POST" enctype="multipart/form-data">
<input type="file" name="file" required>
<button type="submit" name="files" class="btn btn-primary btn-xs">
Submit
</button>
<?php
if(isset($_POST['files']))
{
$userid = $row['stall_id'];
$a = $_FILES['file']['name'];
$ab = $_FILES['file']['tmp_name'];
$location = "".$a;
move_uploaded_file($ab, "../pictures/".$location);
$sql2 = $conn->prepare("UPDATE stall SET file = ? WHERE stall_id = ?");
$sql2->execute(array($location,$userid));
if($sql){
echo '
<script>
window.location = "stalls.php"
</script>';
}
}
?>
</td>
I Figured it out my self,
<td>
<form method="POST" enctype="multipart/form-data">
<input type="file" name="file" required>
<input type="hidden" name="stall_id" value="<?php echo $value['stall_id']?>">
<button type="submit" name="files" class="btn btn-primary btn-xs">
Submit
</button>
<?php
if(isset($_POST['files']))
{
$userid = $_POST['stall_id'];
$a = $_FILES['file']['name'];
$ab = $_FILES['file']['tmp_name'];
$location = "".$a;
move_uploaded_file($ab, "../pictures/".$location);
$sql2 = $conn->prepare("UPDATE stall SET file = ? WHERE stall_id = ?");
$sql2->execute(array($location,$userid));
if($sql2){
echo '
<script>
window.location = "stalls.php"
</script>';
}
}
?>
</td>
Please Bind Parameter After Prepare statement. check docs- http://php.net/manual/en/mysqli.prepare.php
in if condition put $update(return value of execution) instead of sql
close </form> tag.
check all variables having data. check with var_dump(), print_r() or echo() methods.
<td>
<form method="POST" enctype="multipart/form-data">
<input type="file" name="file" required>
<button type="submit" name="files" class="btn btn-primary btn-xs">
Submit
</button>
</form>
</td>
<?php
if(isset($_POST['files']))
{
$userid = $row['stall_id'];
$a = $_FILES['file']['name'];
$ab = $_FILES['file']['tmp_name'];
$location = "".$a;
move_uploaded_file($ab, "../pictures/".$location);
if( $sql2 = $conn->prepare("UPDATE stall SET file = ? WHERE stall_id = ?"))
{
$sql2->bindParam(1, $location, PDO::PARAM_STR);
$sql2->bindParam(2, $userid, PDO::PARAM_INT);
$update=$sql2->execute();
if($update){
echo '
<script>
window.location = "stalls.php"
</script>';
}
}else{
echo 'sql prepare failed';
}
}
?>
change from
$sql2 = $conn->prepare("UPDATE stall SET file = ? WHERE stall_id = ?");
$sql2->execute(array($location,$userid));
to
$sql2 = $conn->prepare("UPDATE stall SET file = ? WHERE stall_id = ?");
$sql2->bindParam(1, $location, PDO::PARAM_STR);
$sql2->bindParam(2, $userid, PDO::PARAM_INT);
$sql2->execute();

Creating PHP login system

i am trying to build a login system with php , can anyone point me to my error in my code
<?php
session_start();
if(isset($_POST['loginbtn'])){
require_once 'index.php';
require_once 'Database_conx.php';
$emailbox = $_POST ["loginemailbox"];
$loginpasswordbox = $_POST ["loginpasswordbox"];
$loginpasswordbox = md5($loginpasswordbox);
$result = mysqli_query($conn, 'SELECT * FROM Registration where Email = "'.$emailbox.'" and User_Password= "'.$loginpasswordbox.'" ');
if(mysqli_num_rows($result) == 1) {
$_SESSION['loginemailbox'] = $emailbox;
header('Location:home.php');
}
}
?>
and the following html code is found on my index.php
<form id="login" action="login.php" method="post">
<div id ="header_top_login">
<input type="text" class ="form-control" placeholder = "Enter Email" name = "loginemailbox" style="border :0px;">
</div>
<div id = "header_top_password">
<input type="password" class = "form-control" placeholder = "Enter Password" name = "loginpasswordbox" style = "border :0px">
</div>
<div id = "loginbutton">
<a href="login.php" type=" submit" name="loginbtn" class="btn btn-danger pull-right" > Login</a>
</div>
<div id="forget_Password" >
<button type="button" class="btn btn-link">Forget your Password ?</button>
</div>
</form>
can anyone tell me what am doing wrong.
For Submit button Use input instead of a tag.
For example:
<form action="demo_form.php">
Username: <input type="text" name="usrname"><br>
<input type="submit" value="Submit">
</form>
i think you should replace this two line in login.php.
$emailbox = $_POST ["loginemailbox"];
$loginpasswordbox = $_POST ["loginpasswordbox"];
with this.
$emailbox = $_POST["loginemailbox"];
$loginpasswordbox = $_POST["loginpasswordbox"];
remove blank space.

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