image name not showing in database using PHP - php

Mysql Database attribute image name and type
`Image varchar256`
I m trying to upload image name in mysql but issue is image is move to folder as per requirement but name of image is not showing in database. kindly help...
<form method="post" enctype="multipart/form-data" >
<div class="content table-responsive table-full-width">
<div class="title" style="margin-left: 7%;"> Product ID</div>
<input class="form-control" type="text" name="P_id" placeholder="Product ID" readonly/>
<div class="title" style="margin-left: 7%;" >Product Name</div>
<input class="form-control" type="text" name="P_Name" placeholder="Product Name" required/>
<div class="title" style="margin-left: 7%;">Descriptiom</div>
<textarea class="form-control" type="text" name="P_Description" placeholder="Description"required></textarea>
<div class="title" style="margin-left: 7%;">Category</div>
<!-- Category Add in Drop Down-->
<select name="C_id" class="form-control" required>
<option>Select Category</option>
<?php
$get_category= "select * from category";
$run_category= mysqli_query($con,$get_category);
while($row_category=mysqli_fetch_array($run_category))
{
$C_id=$row_category['C_id'];
$C_Name=$row_category['C_Name'];
echo "<option value='$C_id'>$C_Name</option>";
}
?>
</select><!-- End Conde-->
<div class="title" style="margin-left: 7%;">Price</div>
<input class="form-control" type="text" name="P_Price" placeholder="Enter Price"required/>
<div class="title" style="margin-left: 7%;">Quantity</div>
<input class="form-control" type="text" name="P_Quantity" placeholder="Enter Quantity"required/>
<div class="title" style="margin-left: 7%;">Image</div>
<input class="form-control" type="file" name="image" placeholder="Upload Image"required accept=""/>
<div class="navbar-form">
<input type="submit" class="btn btn-primary " name="Insert" value="Insert"style="margin-left: 7%;"/>
<label name="Label" ></label>
</div>
<div class="navbar-form">
+Add Category
+Add Brand
</div>
</div>
</form>
The Example which move image to folder but image name not showing in database
<?php
if(isset($_POST['Insert'])){
$P_id=$_POST['P_id'];
$P_Name=$_POST['P_Name'];
$P_Description= $_POST['P_Description'];
$CId=$_POST['C_id'];
$P_Price=$_POST['P_Price'];
$P_Quantity=$_POST['P_Quantity'];
//image names
$PImage = $_FILES['image']['name'];
//image temp names
$tempname = $_FILES["image"]["tmp_name"];
//for image upload on folder
move_uploaded_file($tempname,"Images/$PImage");
if($PName='' OR $PDescription='' OR $C_id='' OR $Price='' OR $Quantity='' OR $PImage='' )
{
echo"<script>alert('please fill fields')</script>";
}
else {
$insert_Product = "INSERT INTO `product`(`P_id`, `P_Name`, `P_Description`, `Price`, `Quantity`, `C_Id`, `Image`) VALUES ('','$P_Name','$P_Description','$P_Price','$P_Quantity','$CId','$PImage')";
$run_Product = mysqli_query($con, $insert_Product);
if($run_Product){
$label= "Label";
$label= "Enter Data successfully";
echo $label;
}
}
}
?>
How can i resolve my issue ?

Try this Query..
if(empty($P_Name) || empty($P_Description) || empty($P_Price) || empty($P_Quantity) || empty($PImage) || empty($CId))
{
echo"<script>alert('please fill fields')</script>";
}
else {
$insert_Product = "INSERT INTO `product`(`P_id`, `P_Name`, `P_Description`, `Price`, `Quantity`, `C_Id`, `Image`) VALUES ('','$P_Name','$P_Description','$P_Price','$P_Quantity','$CId','$PImage')";
.
.
.
.
}
Hope this helps..

This code is use to save image path into database.
In this first line get you image into file variable.
Second line use to get file extension.
Third line is used to change your image file name
Fourth line is use to move image into your given folder name
And the last line is getting image name with folder path
$file = $_FILES['image'];
$extension = $file->getClientOriginalExtension();
$imageName = 'anything'.time().'.'.$extension;
$file->move(public_path('/foldername'), $imageName);
$imageFile = '/foldername/'.$imageName;
Insert $imageFile into your database image column.
It works for both.. image move to your folder and save image path into database.

Related

How to insert images with text data to database in php using mysql.?

I have a long-form with some images upload areas. I need to insert images with text data to MySQL database The form and query code as follows. If PHP codes are not correct, tell me how to do it correctly.?
<div class="container">
<div class="row">
<div class="col-md-4">
<div class="form_main">
<h4 class="heading"><strong>Add</strong> Vehicle <span></span></h4>
<div class="form">
<form action="insert.php" method="POST" id="contactFrm" enctype="multipart/form-data" name="contactFrm">
<select class="form-control form-control-lg" name="brand">
<option value="TATA" >TATA</option>
<option value="TOYOTA">TOYOTA</option>
<option value="DAIHATSu">DAIHATSU</option>
</select>
<input type="text" required="" placeholder="Model" name="model" class="txt">
<div class="form-group">
<label for="exampleFormControlFile1">Front</label>
<input type="file" name="vehi_front" class="form-control-file" id="exampleFormControlFile1">
</div>
<div class="form-group">
<label for="exampleFormControlFile1">Left</label>
<input type="file" name="vehi_left" class="form-control-file" id="exampleFormControlFile1">
</div>
<div class="form-group">
<label for="exampleFormControlFile1">Right</label>
<input type="file" name="vehi_right" class="form-control-file" id="exampleFormControlFile1">
</div>
<div class="form-group">
<label for="exampleFormControlFile1">Rear</label>
<input type="file" name="vehi_back" class="form-control-file" id="exampleFormControlFile1">
</div>
<textarea placeholder="Other" name="other" type="text" class="txt_3"></textarea>
<input type="submit" value="submit" name="submit" class="txt2">
</form>
</div>
</div>
</div>
</div>
</div>
This is the insert query code.
<?php
include("../inc/conn.php");
$brand=$_POST['brand'];
$model=$_POST['model'];
$vehi_front=$_POST['vehi_front'];
$vehi_left=$_POST['vehi_left'];
$vehi_right=$_POST['vehi_right'];
$vehi_back=$_POST['vehi_back'];
$other=$_POST['other'];
{
$sql = "INSERT INTO vehicle(brand,model,vehi_front,vehi_left,vehi_right,vehi_back,other) VALUES ('{$brand}','{$model}','{$vehi_front}','{$vehi_left}','{$vehi_right}','{$vehi_back}','{$other}')";
if(mysqli_query($con,$sql))
{
header("location:add_vehicle.php?msg=Successfully Saved !");
}
}
?>
you must create image uploader function
in php $_POST['image_input_name'] return you null
you must use $_FILE
function uploadPic($file_input_name, $path)
{
if (isset($_FILES[$file_input_name])) {
$file = $_FILES[$file_input_name];
// for bin2hex and random_bytes you must use php > 7
$new_name = (string)bin2hex(random_bytes(32));
$extension = ".jpg";
$final_name = $new_name . $extension;
move_uploaded_file($file['tmp_name'], $path . $final_name);
return $path . $final_name;
}
}
first line check for image
2 get the file and put in into $file
3 change the name for security
4 change the extension for more security
// user upload a shel.php. in function we change the name and extension
// for exp shel.php converted to hs7f4w8r5c1f4s5d9t6g3s149748654asdasd.jpg
5 add name and extension in var
6 we move uploaded pic to path
7 we return the address and name of pic
and in your new code here
<?php
include("../inc/conn.php");
$brand = $_POST['brand'];
$model = $_POST['model'];
// in if we check for image exist
if ($_FILES['vehi_front']['tmp_name'] != "") {
$vehi_front = $this->uploadPic("vehi_front", "/path/to/save/image");
}
if ($_FILES['vehi_left']['tmp_name'] != "") {
$vehi_left = $this->uploadPic("vehi_left", "/path/to/save/image");
}
if ($_FILES['vehi_right']['tmp_name'] != "") {
$vehi_right = $this->uploadPic("vehi_right", "/path/to/save/image");
}
if ($_FILES['vehi_back']['tmp_name'] != "") {
$vehi_right = $this->uploadPic("vehi_back", "/path/to/save/image");
}
$other = $_POST['other'];
{
$sql = "INSERT INTO vehicle(brand,model,vehi_front,vehi_left,vehi_right,vehi_back,other) VALUES ('{$brand}','{$model}','{$vehi_front}','{$vehi_left}','{$vehi_right}','{$vehi_back}','{$other}')";
if (mysqli_query($con, $sql)) {
header("location:add_vehicle.php?msg=Successfully Saved !");
}
}
?>
You can do this using $_FILES variable
see reference here: https://www.php.net/manual/en/reserved.variables.files.php

Inserting into two database tables, parent and child, not working, likely something small

If anyone can point me to a similar solution, I initally had only one table (Dog) with basic data and one profile img.
I decided I would make an extra table, that will have the dogId as a FK for additional images.
My code works perfect if I keep the tables separate. When I create the FK in the images table, the code will not insert any data into the DB. I think the issue is something small.
i have two database tables, one is for a Dog includes name , age, gender etc and one profile image.
The second is the new table, for additional images, with a foreign key of dog Id in order to reference the dog the additional images belong to.
The issue i am having is, the basic upload of a dog profile was working perfect (uploading one main image and data, and entering into the database).
I made a new table for additional image uploads, and put a foreign key of the main Dog table into it. (id). this was to reference the dog the additional pics belong to.
I amended the code to include an additional form element:
<div class="form-group">
<label for="extra_images">Choose Images</label>
<input type="file" class="form-control"
name="userfile[]" value="" multiple="">
</div>
It will not upload to either table now, or show the multi images on the show_dog page (included last in code)
I am not sure if I am referencing the Foreign key correctly, or inserting that part correct. this could relate to:
$sql = "INSERT IGNORE INTO dog_img (name, img_dir, id) VALUES('$name',
'$img_dir', '$id')";
which is in the Functions section for:
if(isset($_FILES['userfile'])){......
//CODE BELOW
<form class="" action="create_dog.php" method="post"
enctype="multipart/form-data">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" name="name" <?
php echo $name ?> placeholder="Enter Name" value="" required>
</div>
<div class="form-group">
<label for="age">Age:</label>
<input type="text" class="form-control" name="age"
placeholder="Enter Age" value="" required>
</div>
<div class="form-group">
<label for="gender">Gender:</label>
<input type="text" class="form-control" name="gender"
placeholder="Enter Gender" value="" required>
</div>
<div class="form-group">
<label for="breed">Breed</label>
<input type="text" class="form-control" name="breed"
placeholder="Enter Breed" value="" required>
</div>
<div class="form-group">
<label for="description">Description</label>
<input type="text" class="form-control"
name="description" placeholder="Enter a Description" value="" required>
</div>
<div class="form-group">
<label for="image">Choose Image</label>
<input type="file" class="form-control" name="image"
value="">
</div>
<div class="form-group">
<label for="extra_images">Choose Images</label>
<input type="file" class="form-control"
name="userfile[]" value="" multiple="">
</div>
<div class="form-group">
<button type="submit" name="create_dog_btn" value
="upload" class="btn btn-primary waves">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
//functions
if (isset($_POST['create_dog_btn'])) {
create_new_dog();
}
function create_new_dog(){
global $conn;
global $upload_dir;
if (isset($_GET['id'])) {
$id = $_GET['id'];
$id=mysqli_real_escape_string($conn,trim($_GET['id']));
echo $id;
$sql = "SELECT * from dog where id=".$id;
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_assoc($result);
}else {
$errorMsg = 'Could not Find Any Record';
}
}
//validation....... (cut out for tidyness sake)
if(empty($errors)){
$imgExt = strtolower(pathinfo($imgName,
PATHINFO_EXTENSION));
$allowExt = array('jpeg', 'jpg', 'png', 'gif');
$userPic = time().'_'.rand(1000,9999).'.'.$imgExt;
if(in_array($imgExt, $allowExt)){
if($imgSize < 5000000){
move_uploaded_file($imgTmp
,$upload_dir.$userPic);
}else{
$errors[] = 'Image too large';
}
}else{
$errors[] = 'Please select a valid image';
}
}
elseif(!empty($errors)){
foreach ($errors as $msg) {
echo "- $msg <br/>";
}
echo "<h4><br/>Please enter correct details!</h4>";
}
if(!isset($errors)){
$sql = "INSERT INTO dog(name, age, gender, breed,
description, image)
values('".$name."', '".$age."',
'".$gender."', '".$breed."', '".$description."',
'".$userPic."')";
$result = mysqli_query($conn, $sql);
if($result){
$successMsg = 'New dog added successfully';
header('Location: index_admin.php');
}else{
$errors[] = 'Error adding this record.
'.mysqli_error($conn);
if(!empty($errors)){
foreach ($errors as $msg) {
echo "- $msg <br/>";
}
//echo $errorMsg[];
}
}
}
}
function reArrayFiles($file_post){
$file_ary = array();
$file_count = count($file_post['name']);
$file_keys = array_keys($file_post);
for($i=0; $i < $file_count; $i ++){
foreach($file_keys as $key){
$file_ary[$i][$key] = $file_post[$key][$i];
}
}
return $file_ary;
}
if(isset($_FILES['userfile'])){
$phpFileUploadsErrors = array(
0=> 'there is no error, the fle uploaded with success',
1=> 'the file exceeds the upload max file size in php ini',
2=> 'the file exceeds the upload max file size specified in HTML
form',
3=> 'uploaded file only partially uploaded',
4=> 'no file was uploaded',
5=> 'missing a temporary folder',
6=> 'failed to write file to disk',
7=> 'a php extension stopped the file upload',
);
$file_array = reArrayFiles($_FILES['userfile']);
pre_r($_FILES);
for($i=0; $i<count($file_array); $i++){
if($file_array[$i]['error']){
?> <div class = "alert alert-danger">
<?php echo $file_array[$i]['name'].' -
'.$phpFileUploadsErrors[$file_array[$i]['error']];
?> </div> <?php
}
else{
$extensions = array('jpg', 'png', 'gif', 'jpeg');
$file_ext = explode('.', $file_array[$i]['name']);
//pre_r( $file_ext); die;
//image name variable at index 0 as per associative arrays
$name = $file_ext[0];
$name = preg_replace("!-!"," ", $name);
$name = ucwords($name);
$file_ext = end($file_ext);
//convert any uppercase extensions to lowercase whilst checking valid
extension
if(!in_array(strtolower($file_ext), $extensions)){
?> <div class = "alert alert-danger">
<?php echo "{$file_array[$i]['name']} Invalid file extension!";
?> </div> <?php
}
else{
$img_dir = "../uploads/".$file_array[$i]['name'];
move_uploaded_file($file_array[$i]['tmp_name'],$img_dir);
$sql = "INSERT IGNORE INTO dog_img (name, img_dir, id)
VALUES('$name',
'$img_dir', '$id')";
$conn->query($sql) or die($conn->error);
?> <div class = "alert alert-success">
<?php echo $file_array[$i]['name'].' -
'.$phpFileUploadsErrors[$file_array[$i]['error']];
?> </div> <?php
}
}
}
} //END OF FUNCTIONS
//SHOW DOG THE MULTI UPLOAD IMAGES WILL NOT DISPLAY
<div class="card-header">
SHOW DOG
</div>
<div class="card-body">
<div class="row">
<div class="col-md">
<img src="<?php echo $upload_dir.$row['image'] ?>"
height="200">
</div>
<div class="col-md">
<h5 class="form-control"><i class="fa fa-user-tag">
<span><?php echo $row['name'] ?></span>
</i></h5>
<h5 class="form-control"><i class="fa fa-mobile-alt">
<span><?php echo $row['age'] ?></span>
</i></h5>
<h5 class="form-control"><i class="fa fa-mobile-alt">
<span><?php echo $row['gender'] ?></span>
</i></h5>
<h5 class="form-control"><i class="fas fa-dog">
<span><?php echo $row['breed'] ?></span>
</i></h5>
<h5 class="form-control"><i class="fas fa-dog">
<span><?php echo $row['description'] ?></span>
</i></h5>
<a class="btn btn-outline-danger"
href="index_admin.php"><i class="fa fa-sign-out-alt"></i>
<span>Back</span></a>
</div>
</div>
</div>
</div>
</div>
<?php
$result = $conn-> query("SELECT * FROM dog_img") or die($conn-
>error);
echo "test";
while($data = $result->fetch_assoc()){
echo "<h2>{$data['name']} </h2>";
echo "<img src='{$data['img_dir']}' width ='40%'
height='40%'>";
}
?>
</div>
Any help would be appreciated, I accept my code is very long, but I am really stuck with this.
thank you.

New to Ubuntu cant upload images to directory for webpage through xampp worked fine on windows

Hi I'm new to Linux Ubuntu 18.04.
I have installed the xampp web server.
I have php code which works fine on windows environment with xampp. However i have now switched over to Linux and when i complete the page to upload an image to a directory it looks like the page completes processing but the directory itself is empty. Can anybody please help i have tried the permissions as other forum and videos have mentioned but this has made no difference.
I am new to Linux so please be patient with me
Thanks for your time
Kunal
Edit My code as said it may be slight cumbersome i'm learning php
all database calls work fine.
<?php
require_once $_SERVER['DOCUMENT_ROOT'].'/ECommerce/core/init.php';
include 'includes/head.php';
include 'includes/navigation.php';
$dbpath='';
if(isset($_GET['add'])||isset($_GET['edit'])){
$brandQuery = $db->query("SELECT * FROM brand ORDER BY brand");
$parentQuery = $db->query("SELECT * FROM catergories WHERE parent =0 ORDER BY category");
$title =((isset($_POST['title'])&& $_POST['title'] !='')?sanitize($_POST['title']):'');
$brand =((isset($_POST['brand']) && !empty($_POST['brand']))?sanitize($_POST['brand']):'');
$parent =((isset($_POST['parent']) && !empty($_POST['parent']))?sanitize($_POST['parent']):'');
$category =((isset($_POST['child'])) && !empty($_POST['child'])?sanitize($_POST['child']):'');
$price =((isset($_POST['price'])&& $_POST['price'] !='')?sanitize($_POST['price']):'');
$list_price =((isset($_POST['list_price'])&& $_POST['list_price'] !='')?sanitize($_POST['list_price']):'');
$description =((isset($_POST['description'])&& $_POST['description'] !='')?sanitize($_POST['description']):'');
$available =((isset($_POST['available'])&& $_POST['available'] !='')?sanitize($_POST['available']):'');
$size =((isset($_POST['size'])&& $_POST['size'] !='')?sanitize($_POST['size']):'');
$saved_image='';
if(isset($_GET['edit'])){
$edit_id = (int)$_GET['edit'];
$productResults= $db->query("SELECT * FROM products WHERE id ='$edit_id'");
$product = mysqli_fetch_assoc($productResults);
if (isset($_GET['delete_image'])){
$image_url = $_SERVER['DOCUMENT_ROOT'].$product['image'];echo $image_url;
unlink($image_url);
$db->query("UPDATE products SET image=''WHERE id ='$edit_id'");
header('Location: products.php?edit='.$edit_id);
}
$category = ((isset($_POST['child']) && $_POST['child']!= '')?sanitize($_POST['child']):$product['categories']);
$title = ((isset($_POST['title']) && $_POST['title']!='')?sanitize($_POST['title']):$product['title']);
$brand = ((isset($_POST['brand']) && $_POST['brand']!='')?sanitize($_POST['brand']):$product['brand']);
$parentQ = $db->query("SELECT * FROM catergories WHERE id ='$category'");
$parentResult= mysqli_fetch_assoc($parentQ);
$parent = ((isset($_POST['parent']) && $_POST['parent'] !='')?sanitize($_POST['parent']):$parentResult['parent']);
$price = ((isset($_POST['price']) && $_POST['price']!='')?sanitize($_POST['price']):$product['price']);
$list_price = ((isset($_POST['list_price']) && $_POST['list_price']!='')?sanitize($_POST['list_price']):$product['list_price']);
$description = ((isset($_POST['description']) && $_POST['description']!='')?sanitize($_POST['description']):$product['description']);
$available = ((isset($_POST['available']) && $_POST['available']!='')?sanitize($_POST['available']):$product['Available']);
$size = ((isset($_POST['size']) && $_POST['size']!='')?sanitize($_POST['size']):$product['size']);
$saved_image=(($product['image'] !='')?$product['image']:'');
$dbpath=$saved_image;
}
if($_POST){
$categories =sanitize($_POST['child']);
$price =sanitize($_POST['price']);
$list_price =sanitize($_POST['list_price']);
$size =sanitize($_POST['size']);
$description =sanitize($_POST['description']);
$errors = array();
$size= sanitize($_POST['size']);
$dbPath='';
$required = array('title','price','parent','child');
$available = sanitize($_POST['available']);
foreach ($required as $field) {
if($_POST[$field]== ''){
$errors[] ='All fields With an Asterisk are required.';
break;
}
}
if(!empty($_FILES)) {
var_dump ($_FILES);
$photo=$_FILES['photo'];
$name=$photo['name'];
$nameArray = explode('.',$name);
$fileExt = $nameArray[1];
$mime = explode ('/',$photo['type']);
$mimeType=$mime[0];
$mimeExt =$mime[1];
$tmpLoc=$photo['tmp_name'];
$fileSize=$photo['size'];
$allowed= array('png','jpg','JPEG','GIF');
$uploadName = md5(microtime()).'.'.$fileExt;
$uploadPath= '/ECommerce/stock/'.$uploadName;
$dbpath ='/ECommerce/stock/'.$uploadName;
if($mimeType !='image'){
$errors[]='The File must be an image';
}
if(!in_array($fileExt,$allowed)){
$errors[]='The file extenstion must be a PNG, JPG,JPEG or GIF.';
}
if($fileSize > 15000000){
$errors[]='The file size must be under 15MB.';
}
if ($fileExt != $mimeExt && ($mimeExt ==='jpeg' && $fileExt !='jpg')){
$errors[]='The File extension does not match the file';
}
}
if(!empty($errors)){
echo display_errors($errors);
}else{
//upload file and insert into database
move_uploaded_file($tmpLoc,$uploadPath);
$insertSQL="INSERT INTO products (`title`,`price`,`list_price`,`brand`,`categories`,`size`,`image`,`description`,`Available`)
VALUES('$title','$price','$list_price','$brand','$category','$size','$dbpath','$description','$available')";
if(isset($_GET['edit'])){
$insertSQL="UPDATE products SET title ='$title', price = '$price', list_price = '$list_price',
brand='$brand', categories ='$category', size='$size' , Available='$available',image='$dbpath',description='$description' WHERE id='$edit_id'";
}
$db->query($insertSQL);
header('Location: products.php');
}
}
?>
<h2 class="text-center"><?=((isset($_GET['edit']))?'Edit A ':'Add A New');?>Product</h2><hr>
<form action="products.php?<?=((isset($_GET['edit']))?'edit='.$edit_id:'add=1');?>" method="POST" ENCTYPE="multipart/form-data">
<div class="form-group col-md-3">
<label for="title">Title*:</label>
<input type="text" name="title"class="form-control" id="title" value="<?=$title;?>">
</div>
<div class="form-group col-md-3">
<label for="brand">Brand:</label>
<select class="form-control" id="brand" name="brand">
<option value=""<?=(($brand =='')?' selected':'');?>></option>
<?php while($b=mysqli_fetch_assoc($brandQuery)): ?>
<option value="<?=$b['id'];?>"<?=(($brand == $b['id'])?' selected':'');?>><?=$b['brand'];?></option>
<?php endwhile;?>
</select>
</div>
<div class="form-group col-md-3">
<label for="parent">Parent Category*:</label>
<select class="form-control" id="parent" name="parent">
<option value=""<?=(($parent =='')?' selected':'');?>></option>
<?php while($p= mysqli_fetch_assoc($parentQuery)): ?>
<option value="<?=$p['id'];?>"<?=(($parent == $p['id'])?' selected':'');?>><?=$p['category'];?></option>
<?php endwhile; ?>
</select>
</div>
<div class="form-group col-md-3">
<label for="child">Child Category*:</label>
<select id="child" name="child" class="form-control">
</select>
</div>
<div class="form-group col-md-3">
<label for="price">Price*:</label>
<input type="text" id="price" name="price" class="form-control" value="<?=$price;?>">
</div>
<div class="form-group col-md-3">
<label for="price">List Price*:</label>
<input type="text" id="list_price" name="list_price" class="form-control" value="<?=$list_price;?>">
</div>
<div class="form-group col-md-3">
<label>Size*:</label>
<input type="text" id="size" name="size" class="form-control" value="<?=$size;?>">
</div>
<div class="form-group col-md-3">
<label>Available:</label>
<input type="text" id="size" name="available" class="form-control" value="<?=$available;?>">
</div>
<br>
<div class="form-group col-md-6">
<?php if($saved_image !=''): ?>
<div class="saved-image"><img src="<?=$saved_image;?>" alt="saved image"/><br>
Delete Image
</div>
<?php else: ?>
<label for="photo">Product Photo:</label>
<input type="file" name="photo" id="photo" class="form-control" accept="image/*" >
<?php endif;?>
</div>
<div class="form-group col-md-6">
<label for="description">Description:</label>
<textarea id="description" name="description" class="form-control" rows="6"><?=$description;?></textarea>
</div>
<div class="form-group pull-right">
Cancel
<input type="submit" value="<?=((isset($_GET['edit']))?'Edit ':'Add ');?> Product" class="btn btn-success pull-left">
</div><div class ="clearfix"></div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<?php }else{
$sql = "SELECT * FROM products WHERE deleted = 0";
$presults =$db->query($sql);
if (isset($_GET['featured'])){
$id = (int)$_GET['id'];
$featured = (int)$_GET['featured'];
$featuredsql = "UPDATE products SET featured ='$featured' WHERE id='$id'";
$db->query($featuredsql);
header('Location: products.php');
}
?>
<h2 class="text-center">Products </h2>
Add Product<div class="clearfix"></div>
<hr>
<table class="table table-bordered table-condensed table-striped">
<thead><th></th><th>Product</th><th>Price</th><th>Category</th><th>Featured</th><th>Sold</th></thead>
<tbody>
<?php while($product = mysqli_fetch_assoc($presults)):
$childID= $product['categories'];
$catsql="SELECT* FROM catergories WHERE id = '$childID'";
$result=$db->query($catsql);
$child= mysqli_fetch_assoc($result);
$parentID = $child['parent'];
$psql="SELECT * FROM catergories WHERE id ='$parentID'";
$presult=$db->query($psql);
$parent= mysqli_fetch_assoc($presult);
$category = $parent['category'].'-'.$child['category'];
?>
<tr>
<td>
<span class="glyphicon glyphicon-pencil"></span>
<span class="glyphicon glyphicon-remove"></span>
</td>
<td><?=$product['title'];?></td>
<td><?=money($product['price']);?></td>
<td><?=$category;?></td>
<td><a href="products.php?featured=<?=(($product['featured']==0)?'1':'0')?>&id=<?=$product['id'];?>" class="btn btn-xs btn-default" >
<span class="glyphicon glyphicon-<?=(($product['featured']==1)?'minus':'plus');?>"></span>
</a>&nbsp <?=(($product['featured']== 1)?'Featured Product':'');?></td>
<td>0</td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
<?php
} include 'includes/footer.php';?>
<script>
jQuery('document').ready(function(){
get_child_options('<?=$category;?>');
});
</script>
?>
Chane
$uploadPath= '/ECommerce/stock/'.$uploadName;
to
$uploadPath=$_SERVER['DOCUMENT_ROOT'] . "/ECommerce/stock/".$uploadName;
Linux is case sensitive, have you specified paths correctly to match the case of the folders on the file system?
Is the folder within your webroot - if not, you may have to edit the apache config to set apache permissions for accessing that folder (not just the folder permissions)
Have you looked in the error.log to see what the error output is from PHP. Windows typically has display errors on, this might not be on for a Linux server by default so you'd be missing the error output.
Looking briefly at your code, though not knowing anything else like file name, folder name - you check for file extensions but have not lowercased all (input extension and array to compare with) to ensure case sensitivity is not an issue here. For example file.JPG and file.jpeg will not match your array.
Secondly youn don't check the result of move_uploaded_file, this might help to be sure it succeeded at this point, or not. As mentioned earlier, do check the error log.
Just to add, this code is full of security vulnerabilities - fine for starting out learning but I wouldn't go putting this into production anywhere.

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!

Failed to upload a file in PHP

I try to upload an image, but it is not working. Other variables I have set are inserted into database, but image file is not... I was trying to check submit with isset, but it is not working. Where is my error?
Thanks for your help.
PHP file:
<?php
include ('includes/config.php');
$mysqli = new mysqli(DB_SERVER,DB_UNAME,DB_PASSWD,DB_NAME);
if($mysqli->connect_errno) {
echo "MYSQLI connect error no {$mysqli->connect_errno} : {$mysqli->connect_error}";
die();
}
$itemcode = $_POST['icode'];
$itemname = $_POST['iname'];
$brandname = $_POST['brandname'];
$upload = basename ($_FILES['upload']['name']);
$path = "img/";
if(!empty($upload)) {
$i1 = strrpos($upload,".");
if (!$i1) {
return "";
}
$l1 = strlen($upload) - $i1;
$ext1 = substr($upload,$i1+1,$l1);
$ext1 = strtolower($ext1);
$news_name1=time()+(1).'.'.$ext1;
$newname1 = $path.$news_name1;
$copied1 = copy($_FILES['upload']['tmp_name'], $newname1);
} else {
$news_name1 = '';
}
$iadd = $mysqli->prepare("INSERT INTO table_item (`itemcode`,`itemname`,`brandname`,`upload`) VALUES ('".$itemcode."', '".$itemname."','".$brandname."','".$news_name1."') ");
$iadd->execute();
$iadd->close();
$mysqli->close();
?>
This is my HTML file:
<form class="cmxform form-horizontal tasi-form" name="form2" id="form2" method="post" action="">
<div class="form-group ">
<label for="icode" class="control-label col-lg-2">Item Code</label>
<div class="col-lg-10">
<input class=" form-control" id="icode" name="icode" type="text" />
</div>
</div>
<div class="form-group ">
<label for="iname" class="control-label col-lg-2">Item Name</label>
<div class="col-lg-10">
<input class=" form-control" id="iname" name="iname" type="text" />
</div>
</div>
<div class="form-group ">
<label for="brandname" class="control-label col-lg-2">Brand Name</label>
<div class="col-lg-10">
<input class=" form-control" id="brandname" name="brandname" type="text" />
</div>
</div>
<fieldset style="width:48%; float:left;"> <!-- to make two field float next to one another, adjust values accordingly -->
<label>Doc 2</label>
<input style="margin: 0 10px;" type="file" name="upload" size="50">
</fieldset>
Add 'enctype="multipart/form-data"' to your form tag attributes, you can read more about file uploading here.
Also consider checking the values of the post, because your current method can get you sql injections
add form attribute enctype="multipart/form-data"
You have not proper syntax used and also use 'enctype="multipart/form-data"'.
I have implemented your code
<?php
include ('includes/config.php');
$mysqli = new mysqli(DB_SERVER,DB_UNAME,DB_PASSWD,DB_NAME);
if($mysqli->connect_errno){
echo "MYSQLI connect error no {$mysqli->connect_errno} : {$mysqli->connect_error}";
die();
}
$itemcode = $_POST['icode'];
$itemname = $_POST['iname'];
$brandname = $_POST['brandname'];
$upload = basename ($_FILES['upload']['name']);
$path = "img/";
if(!empty($upload)){
$i1 = strrpos($upload,".");
if (!$i1) { return ""; }
$l1 = strlen($upload) - $i1;
$ext1 = substr($upload,$i1+1,$l1);
$ext1 = strtolower($ext1);
$news_name1=time()+(1).'.'.$ext1;
$newname1 = $path.$news_name1;
$copied1 = $_FILES['upload']['tmp_name'], $newname1;
}else{
$news_name1 = '';
}
$iadd = $mysqli->prepare("INSERT INTO table_item (`itemcode`,`itemname`,`brandname`,`upload`) VALUES ('".$itemcode."', '".$itemname."','".$brandname."','".$news_name1."') ");
$iadd->execute();
$iadd->close();
$mysqli->close();
?>

Categories