inserting multiple images into a mysql database - php

I am creating a form to insert images into a slider, with a maximum of 10 slides. When inserting the images i need the option of being able to choose maybe just 2,3 or 4 slides for example. But when i try to inset less than the 10 image, it does not insert into the database.
Here is what i have thus far;
try {
//$max_size = 2097152; This is to do, not part of question
$allowed = array('jpg', 'jpeg', 'png');
$img_1 = $_FILES['slider_1']['name'];
$extn = strtolower(end(explode('.', $img_1)));
$temp = $_FILES['slider_1']['tmp_name'];
if(in_array($extn, $allowed) === true) {
$slider_1 = 'data/' . md5(time().uniqid()) . '.' . $extn;
move_uploaded_file($temp, $slider_1);
}
//This works upto this point
$insert = DB::getInstance()->insert('slider', array(
'main' => $main,
'slider_1' => $slider_1,
'slider_2' => $slider_2,
'slider_3' => $slider_3,
'slider_4' => $slider_4,
'slider_5' => $slider_5,
'slider_6' => $slider_6,
'slider_7' => $slider_7,
'slider_8' => $slider_8,
'slider_9' => $slider_9,
'slider_10' => $slider_10
));
Session::flash('success', '<p class="success">Inserted successfully</p>');
Redirect::to('test.php');
} catch(Exception $e) {
die($e->getMessage());
}
Here is my insert function
public function insert($table, $fields = array()) {
$keys = array_keys($fields);
$values = null;
$x = 1;
foreach($fields as $value) {
$values .= "?";
if($x < count($fields)) {
$values .= ', ';
}
$x++;
}
$sql = "INSERT INTO {$table} (`" . implode('`, `', $keys) . "`) VALUES ({$values})";
if(!$this->query($sql, $fields)->error()) {
return true;
}
return false;
}
And here is my form
<form id="contact-form" method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" enctype="multipart/form-data" autocomplete="off">
<label for="main"><span class="required">*</span> Main Image:</label>
<input type="file" name="main">
<label for="img_set_1"><span class="required">*</span> Image Set 1:</label>
<input type="file" name="slider_1">
<label for="img_set_2"><span class="required">*</span> Image Set 2:</label>
<input type="file" name="slider_2">
<label for="img_set_3"><span class="required">*</span> Image Set 3:</label>
<input type="file" name="slider_3">
<label for="img_set_4"><span class="required">*</span> Image Set 4:</label>
<input type="file" name="slider_4">
<label for="img_set_5"><span class="required">*</span> Image Set 5:</label>
<input type="file" name="slider_5">
<label for="img_set_6"><span class="required">*</span> Image Set 6:</label>
<input type="file" name="slider_6">
<label for="img_set_7"><span class="required">*</span> Image Set 7:</label>
<input type="file" name="slider_7">
<label for="img_set_8"><span class="required">*</span> Image Set 8:</label>
<input type="file" name="slider_8">
<label for="img_set_9"><span class="required">*</span> Image Set 9:</label>
<input type="file" name="slider_9">
<label for="img_set_10"><span class="required">*</span> Image Set 10:</label>
<input type="file" name="slider_10">
<button type="submit">SUBMIT</button>
<input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
</form>
Thanks in advance

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.

image name not showing in database using 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.

Problems on uploading image files

This is my view file where form for image and other data exists:
<?php echo form_open_multipart('Login/client_profile'); ?>
<div class="form-group">
<label>Company Name</label>
<input type="text" class="form-control" name="company_name" >
</div>
<div class="form-group">
<label>Upload Profile Picture</label>
<input type="file" name="profile_pic" accept="image/*" class="form-control" required>
</div>
<div class="form-group">
<label>Mobile Number</label>
<input type="number" class="form-control" name="mobile" required>
</div>
<div class="form-group">
<label>Specialist in</label>
<input type="text" class="form-control" name="specialist_in" >
</div>
<div class="form-group">
<label>Position</label>
<input type="text" class="form-control" name="position" >
</div>
<?php
$data7 = array(
'type' => 'submit',
'value' => 'Update',
'class' => 'btn btn-primary ',
);
echo form_submit($data7);
echo form_close();
?>
This is the controller file Client.php
public function client_profile()
{
$client=$this->input->post();
$client['profile_pic']=$this->input->post('profile_pic');
$this->load->model('Clientmodel');
$email=$this->session->userdata('email_id');
$this->Clientmodel->add_client_details($email,$client);
$ppic['pic']=$this->Clientmodel->get_pic($email);
$config['upload_path'] = './profile/';
$config['allowed_types'] = 'jpg|jif|png|jpeg';
$this->load->library('upload', $config);
$field = 'pic';
if ($this->upload->do_upload($field)) {
$temp = $this->upload->data();
$pic = $temp['file_name'];
}
$this->load->view('client/pro_header',$ppic);
$this->load->view('client/client_dashboard',$client);
}
This is model file Clientmodel.php
public function add_client_details($email, Array $client)
{
return $this->db->where(['email'=>$email])
->update('clients',$client);
}
public function get_pic($login_email)
{
$q=$this->db->where(['email'=>$login_email])
->get('clients');
return $q->row()->profile_pic;
}
After entering all the data all the fields other than image can be fetched using $this->input->post when i try to fetch 'profile_pic' it returns nothing.And the image file name is also not inserted in database.Field 'profile_pic' is there in table 'clients'
This is the for uploading it's not checking any validation
public function upload_docs () {
if($this->input->post('action') == 'Upload') {
$company_name = $input->post('company_name');
$position = $input->post('position');
$mobile = $input->post('mobile');
$specialist_in = $input->post('specialist_in');
// capture all your variable like this
$file_path = './assets/images/uploads';
if ($_FILES["profile_pic"]["error"] > 0) {
$data['msg'] = 'your message';
} else {
if(!is_dir($file_path)) #mkdir($file_path, 0777, true);
if (move_uploaded_file($_FILES['profile_pic']['tmp_name'], $file_path.'/'.$_FILES['profile_pic']['name'])) {
$upload_data = array('company_name'=> $company_name,'mobile'=> $mobile,'specialist_in'=> $specialist_in,'profile_pic' => $_FILES['profile_pic']['name']);
$insert_id = $this->Your_model->addRecord($upload_data);
if ($insert_id) {
// redirect('admin/index','refresh');
}
}
}
}
$data['title'] = 'upload';
$this->load->view('admin/upload',$data);
}

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