Uploaded Image file extension not getting stored in database - php

here i am trying to upload image to directory and add the path in database.
when i fill form and click submit the image gets uploaded to directory but the file extension doesn't getting saved in database.
for example if i upload image by name mobile-image-small-1.png the file name in database will be just mobile-image-small-1 and it is causing image not to display on web page.what is the problem here
i am using mysql database
here is my php code
// Escape user inputs for security
$product_name = mysqli_real_escape_string($link, $_POST['product_name']);
$product_category = mysqli_real_escape_string($link, $_POST['product_category']);
$product_price = mysqli_real_escape_string($link, $_POST['product_price']);
$pro_url = mysqli_real_escape_string($link, $_POST['pro_url']);
$co_owners = mysqli_real_escape_string($link, $_POST['co_owners']);
// attempt insert query execution
// close connection
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
if($_POST)
{
if($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
if(file_exists("uploaded_images/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
if(move_uploaded_file($_FILES["file"]["tmp_name"],"uploaded_images/" . $_FILES["file"]["name"]))
{
$sql = "INSERT INTO product_list (product_name, product_category, product_price,product_referrence_URL,product_co_owners,product_image_url) VALUES ('$product_name', '$product_category', '$product_price', '$pro_url', '$co_owners', 'files/uploaded_images/".$_FILES['file']['name']."')";
if(mysqli_query($link, $sql)){
header("Location: ../index.php");
}else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
if(mysqli_query($sql))
{
echo "Stored in: " . "uploaded_images/" . $_FILES["file"]["name"];
}
else
{
echo 'Unable to store';
}
}
}
}
}
mysqli_close($link);
?>
here is my form
<form class="form-horizontal" method="post" action="files/insert.php" role="form" enctype="multipart/form-data">
<div class="form-group">
<label class="control-label col-sm-2" for="product_name">Product Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="product_name" id="product_name" placeholder="Iphone 5c" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="pwd">Product Category</label>
<div class="col-sm-10">
<select class="btn-btn-primary form-control" name="product_category">
<option>Mobile</option>
<option>Television</option>
<option>Printer</option>
<option>Watch</option>
<option>Monitor</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="product-pic">Upload your profile picture</label>
<div class="col-sm-10">
<input type="file" class="form-control" name="file" id="file" />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="product_price">Product Price</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="product_price" id="product_price" placeholder="Rs.36,000" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="pro_url">Reference URL</label>
<div class="col-sm-10">
<input type="URL" class="form-control" name="pro_url" id="pro_url" placeholder="http://www.amazon.com" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="co_owners">Co-owners</label>
<div class="col-sm-10">
<select class="btn-btn-primary form-control" name="co_owners">
<option>Select no. owners</option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
<option>7</option>
<option>8</option>
<option>9</option>
<option>10</option>
<option>11</option>
<option>12</option>
<option>13</option>
<option>14</option>
<option>15</option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-success">Add product</button>
</div>
</div>
</form>

As per discussion your database length is 30 and type is varchar and your image length is greater the 30. Thats the reason you half data updated to your database.
So increase the length of your column up to 100 it will take length uo to 100 length.

I think you can use the type field to get this value
$_FILE['file']['type']
Check out the documentation here

Related

I want to add multiple images into MySQL database

I'm working on this feature in my project where I want to add three(3) images along side other details into my database row and I want this images to be in separate columns in one row.... So far below is my code. the code is not working yet... The images and texts are not uploading to the database....
Please help me out guys. What am I doing wrong. Thanks.
Below is my code sample:
//THE PHP SECTION//
<?php
session_start();
include 'includes/config.php';
if (isset($_POST['post']) && isset($_POST['itemtype'])) {
$title = mysqli_real_escape_string($link, $_POST['title']);
$itemtype = mysqli_real_escape_string($link, $_POST['itemtype']);
$description = mysqli_real_escape_string($link, $_POST['description']);
$image1 = $_FILES['image1']['name'];
$image1_tmp_name = $_FILES['image1']['tmp_name'];
$image2 = $_FILES['image2']['name'];
$image2_tmp_name = $_FILES['image2']['tmp_name'];
$image3 = $_FILES['image3']['name'];
$image3_tmp_name = $_FILES['image3']['tmp_name'];
$price = mysqli_real_escape_string($link, $_POST['price']);
$category = mysqli_real_escape_string($link, $_POST['category']);
$name = mysqli_real_escape_string($link, $_POST['name']);
//image file directory
$target1 = 'images/user_ads/'.basename($image1);
$target2 = 'images/user_ads/'.basename($image2);
$target3 = 'images/user_ads/'.basename($image3);
if (move_uploaded_file($_FILES['image1_tmp_name'], $target1)) {
}
if (move_uploaded_file($_FILES['image2_tmp_name'], $target2)) {
}
if (move_uploaded_file($_FILES['image3_tmp_name'], $target3)) {
}
//insert into ost database
$insert = "INSERT INTO products(Title,Product_Type,Description,Image1,Image2,Image3,Price,Category,Name,PostedDate)VALUES('$title','$itemtype','$description','$target1','$target2','$target3','$price','$category','$name',NOW())";
$insertKwary = mysqli_query($link, $insert);
if ($insertKwary) {
$msg = "<div class='alert alert-danger alert-success'>Product Submitted</div>";
}else{
$msg = "<div class='alert alert-danger alert-success'>Product Not Submitted...Try again</div>";
}
}
?>
//THE HTML SECTION//
<div class="col-md-8 col-md-offset-2">
<?php if(isset($msg)) { echo $msg; } ?>
<form action="" method="POST" enctype="multipart/form-data" class="postAdForm" id="postAdForm">
<div class="form-group">
<label for="Ad_title">Item Title</label>
<input type="text" name="title" class="form-control title" id="title" required=""/>
</div>
<div class="form-group">
<label for="itemtype">Item Type</label>
<select class="form-control" name="itemtype" id="itemtype">
<option>Sale</option>
<option>Request</option>
</select>
</div>
<div class="form-group">
<label for="description">Item Description</label>
<textarea name="description" class="form-control description" id="description" rows="7" required=""></textarea>
</div>
<div class="form-group">
<label for="price">First Image</label>
<input type="file" name="image1" class="form-control image1" id="image1" required="" />
</div>
<div class="form-group">
<label for="price">Second Image</label>
<input type="file" name="image2" class="form-control image2" id="image2" required="" />
</div>
<div class="form-group">
<label for="price">Third Image</label>
<input type="file" name="image3" class="form-control image3" id="image3" required="" />
</div>
<div class="form-group">
<label for="price">Price</label>
<input type="text" name="price" class="form-control price" id="price" required="" />
</div>
<div class="form-group">
<label for="category">Item Category</label>
<select class="form-control" name="category" id="category">
<option>Sale</option>
<option>Request</option>
</select>
</div>
<div class="form-group">
<label for="price">Name</label>
<input type="text" name="name" class="form-control name" id="name" required="" readonly="" />
</div>
<div class="form-group">
<input type="submit" name="post" class="btn btn-post post" id="post" value="POST AD" />
</div>
</form>
</div>
I've also attached an image of the error i'm getting..
image of web page showing thee errors i get..error gotten
The error is due to these lines:
if (move_uploaded_file($_FILES['image1_tmp_name'], $target1)) {
}
if (move_uploaded_file($_FILES['image2_tmp_name'], $target2)) {
}
if (move_uploaded_file($_FILES['image3_tmp_name'], $target3)) {
}
You're setting $image1_tmp_name, not $_FILES['image1_tmp_name'].
Try this:
if (move_uploaded_file($image1_tmp_name, $target1)) {
}
if (move_uploaded_file($image2_tmp_name, $target2)) {
}
if (move_uploaded_file($image3_tmp_name, $target3)) {
}
Edit: Using mysqli_error() to print the error helped solve additional issues (Mentioned in comments)

how do I foreach through html input form and insert multiple rows or one based on a selected date field?

how do I foreach through html input form and insert multiple rows or one based on a selected date field? in other words when a user enters "name" "description" and "shift" and then selects either one date or more then one. PHP will then enter the same information for either one new row or multiples based on how many dates were selected.
<?php
if(isset($_REQUEST['submit']))
{
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "xxxx", "xxxx", "xxxx");
// Check connection
if($link === false){
die("| ERROR: Could not connect. " . mysqli_connect_error());
}
$name = mysqli_real_escape_string($link, $_REQUEST['name']);
$desc = mysqli_real_escape_string($link, $_REQUEST['description']);
$shift = mysqli_real_escape_string($link, $_REQUEST['shift']);
$date = mysqli_real_escape_string($link, $_REQUEST['daterange']);
$sql = "insert into db (name,description,shift,evdate) values ('$name', ' $desc','$shift','$date')";
$sql2 = "insert into db (name,description,shift,evdate) values ('$name', ' '$desc','$shift','$insert')";
if ($date=0) {
$result = mysqli_query($link, $sql);
}else{
$daterange = explode(',',$date);
foreach($daterange as $insert) {
$result = mysqli_query($link, $sql2);
}
}
if(mysqli_query($link, $sql)){
echo "";
} else{
echo "| ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
if ($link->multi_query($sql) === TRUE) {
echo "It Worked..... Maybe!!!!!!";
} else {
echo "Error: " . $sql . "<br>" . $link->error;
}
}
$link->close();
?>
<form action="test_insert.php" method="post">
<div class="col col-lg-2 col-lg-offset-0">
<div class="form-group col-lg-offset-0 col-lg-12">
<label for="Name">Employee Name:</label>
<input type="text" name="name" placeholder="First & Last Name" id="name" required>
<p class="help-block col-lg-12">First and Last Name Please.</p>
</div>
</div>
<div class="col col-lg-offset-0 col-lg-2">
<div class="form-group col-lg-12">
<label for="description">Description:</label>
<input type="text" name="description" id="description" placeholder="description..." required>
<p class="help-block">For Example: "Vacation Full Day" or "PTO 2 Hours." </p>
</div>
</div>
<div class="col col-lg-offset-0 col-lg-3">
<label for="shift">Shift:</label><br>
<input type="radio" name="shift" value="First Shift" id="shift" checked> First Shift |
<input type="radio" name="shift" value="Second Shift" id="shift"> Second Shift |
<input type="radio" name="shift" value="Third Shift" id="shift"> Third Shift
<p class="help-block">Select Correct Shift Worked.</p>
</div>
<div class="col col-lg-offset-0 col-lg-3">
<div class="form-group col-lg-10">
<label for="date2">Date/Dates:</label>
<input type="text" id="datepicker1" name="daterange" placeholder="Select Your Date" />
</div>
<div class="form-group col-lg-10">
<label for="date2">Date/Dates:</label>
<input type="text" id="datepicker2" name="daterange" placeholder="Select Your Date" />
</div>
<div class="form-group col-lg-10">
<label for="date2">Date/Dates:</label>
<input type="text" id="datepicker3" name="daterange" placeholder="Select Your Date" />
</div>
<div class="form-group col-lg-10">
<label for="date2">Date/Dates:</label>
<input type="text" id="datepicker4" name="daterange" placeholder="Select Your Date" />
</div>
<div class="form-group col-lg-10">
<label for="date2">Date/Dates:</label>
<input type="text" id="datepicker5" name="daterange" placeholder="Select Your Date" />
</div>
<div class="form-group col-lg-6">
<input type="submit" name="submit" class= "btn btn-primary">
</div>
</div>
</div>
</form>
Think the best way is to use AJAX,
Then with the response as a string you make a table or foreach in php as a string and then use the .html adapter to output the newly made data.
function submitForm(form){
var url = form.attr("action");
var formData = {};
$(form).find("input[name]").each(function (index, node) {
formData[node.name] = node.value;
});
$.post(url, formData).done(function (data) {
$('#showresults').html(result);
});
}

Unable to add data into database in php

<?php
if(isset($_POST["submit"]))
if (!empty($_FILES["uploadImage"]["name"])) {
//Including dbconfig file.
require 'config.php';
$ImageSavefolder = "images/student/";
move_uploaded_file($_FILES["uploadImage"]["tmp_name"] ,
"$ImageSavefolder".$_FILES["uploadImage"]["name"]);
$name = mysqli_real_escape_string($conn, $_POST['name']);
$fathername = mysqli_real_escape_string($conn, $_POST['fathername']);
$htno = mysqli_real_escape_string($conn, $_POST['htno']);
$phoneno = mysqli_real_escape_string($conn, $_POST['phoneno']);
$department = mysqli_real_escape_string($conn, $_POST['department']);
$class = mysqli_real_escape_string($conn, $_POST['class']);
$address = mysqli_real_escape_string($conn, $_POST['address1']);
$address2 = mysqli_real_escape_string($conn, $_POST['address2']);
$city = mysqli_real_escape_string($conn, $_POST['city']);
$state = mysqli_real_escape_string($conn, $_POST['state']);
$zip = mysqli_real_escape_string($conn, $_POST['zip']);
$sql= "INSERT INTO student_detail(name,fathername,htno,phoneno,department,class,address1,address2,city,state,zip) VALUES ('$name','$fathername','$htno','$phoneno','$department','$class','$address','$address2','$city','$state','$zip','".$_FILES['uploadImage']['name']."')";
if(!mysqli_query($conn,$sql))
{
echo "Not Updated";
}
else
{
echo "<br><div class='alert alert-success' role='alert'>Added Sucessfully !</div>";
}
}
?>
This code is not working for adding the following data into database. Did I do anything wrong? Please help me sort the problem.
I already created database with config.php
Form Data
<form method="post" action="" enctype="multipart/form-data">
<div class="form-row">
<div class="form-group col-md-6">
<label for="name">Name</label>
<input type="text" class="form-control" placeholder="Please Enter Name" name="name">
</div>
<div class="form-group col-md-6">
<label for="fathername">Father's Name</label>
<input type="text" class="form-control" placeholder="Please Enter Father's Name" name="fathername">
</div>
<div class="form-group col-md-6">
<label for="htno">Hall Ticket/ Roll No.</label>
<input type="text" class="form-control" placeholder="Please Enter Hall Ticket/ Roll No." name="htno">
</div>
<div class="form-group col-md-6">
<label for="phoneno">Phone Number</label>
<input type="text" class="form-control" placeholder="Please Enter Phone No." name="phoneno">
</div>
<div class="form-group col-md-6">
<label for="department">Department</label>
<select class="form-control" name="department">
<option selected="selected">Choose your Department</option>
<?php
require('config.php');
$result = mysqli_query($conn,"SELECT * FROM department");
while($test= mysqli_fetch_array($result))
{
echo "<option value='".$test['department_name']."'>".$test['department_name']."</option>";
}
?>
</select>
</div>
<div class="form-group col-md-6">
<label for="class">Class</label>
<select class="form-control" name="class">
<option selected="selected">Choose your Class</option>
<?php
require('config.php');
$result = mysqli_query($conn,"SELECT * FROM class");
while($test= mysqli_fetch_array($result))
{
echo "<option value='".$test['class_name']."'>".$test['class_name']."
</option>";
}
?>
</select>
</div>
</div>
<div class="form-group">
<label for="address">Address</label>
<input type="text" class="form-control" placeholder="House No./Flat No." name="address1">
</div>
<div class="form-group">
<label for="address2">Address 2 (Optional)</label>
<input type="text" class="form-control" placeholder="Locality/Area/Street" name="address2">
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="city">City</label>
<input type="text" class="form-control" name="city">
</div>
<div class="form-group col-md-4">
<label for="state">State</label>
<select class="form-control" name="state">
<option selected="selected"name="bihar">bihar</option>
<option>...</option>
</select>
</div>
<div class="form-group col-md-2">
<label for="zip">Zip</label>
<input type="text" class="form-control" name="zip">
</div>
<div class="form-group col-md-6">
<label for="profile">Profile Pic</label><br>
<input type="file" accept="image/*" onchange="loadFile(event)" name="uploadImage" id="uploadImage">
<img id="output" style="width:20%;"/>
<script>
var loadFile = function(event) {
var reader = new FileReader();
reader.onload = function(){
var output = document.getElementById('output');
output.src = reader.result;
};
reader.readAsDataURL(event.target.files[0]);
};
</script>
</div>
</div>
<button type="submit" name="submit" class="btn btn-primary">Submit</button>
</form>
you are trying to insert extra value which is not exist in query see here.
your field
(name,fathername,htno,phoneno,department,class,address1,address2,city,state,zip)
and your values
('$name','$fathername','$htno','$phoneno','$department','$class','$address','$address2','$city','$state','$zip','".$_FILES['uploadImage']['name']."')
you need to do add image field also
your full query
$sql= "INSERT INTO student_detail(name,fathername,htno,phoneno,department,class,address1,address2,city,state,zip,imageFieldName) VALUES ('$name','$fathername','$htno','$phoneno','$department','$class','$address','$address2','$city','$state','$zip','".$_FILES['uploadImage']['name']."')";
<?php
/* dbconnection.php file
$conn = mysqli_connect("localhost","root","12345") or die (mysqli_error());
mysqli_select_db($conn,"student") or die (mysqli_error());
*/
//Including dbconnection file here
include('dbconnection.php');
if(isset($_POST["submit"]))
{
if (!empty($_FILES["uploadImage"]["name"]))
{
$ImageSavefolder = "images/student/";
$name = $_FILES["uploadImage"]["name"];
$tmp_name = $_FILES["uploadImage"]["tmp_name"];
move_uploaded_file(tmp_name, $ImageSavefolder.$name);
$sql = "INSERT INTO students (name,fathername,htno,phoneno,department,class,address1,address2,city,state,zip,image) VALUES ('".$_POST["name"]."','".$_POST["fathername"]."','".$_POST["htno"]."','".$_POST["phoneno"]."','".$_POST["department"]."','".$_POST["class"]."','".$_POST["address1"]."','".$_POST["address2"]."','".$_POST["city"]."','".$_POST["state"]."','".$_POST["zip"]."','".$name."')";
if ($conn->query($sql) === TRUE)
{
echo "<script type= 'text/javascript'>alert('Record Inserted Successfully');</script>";
}
else
{
echo "<script type= 'text/javascript'>alert('Error: " . $sql . "<br>" . $conn->error."');</script>";
}
}
}
?>

getting total value after entering the values in the form and inserting into database using codeigniter

If i select Local Sales from dorpdown and enter DEF, GHI values then the sum of DEF,GHI should be displayed in total value or if i select Inter State,Stock Transfers from dropdown then if we enter ABC value that value should be displayed in total value or else if we select JOB WORK,EXEMPTED SALES from dropdown then the total value should be displayed as zero. The total value which ever we are getting that should be inserted into database.
Controller:
function addinvoice()
{
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<br /><span class="error"> ','</span>');
$this->form_validation->set_rules('user','User');
$this->form_validation->set_rules('freight_charges');
$this->form_validation->set_rules('abc');
$this->form_validation->set_rules('def');
$this->form_validation->set_rules('ghi');
$this->form_validation->set_rules('total');
if($this->form_validation->run()== FALSE)
{
$data['mainpage']='invoice';
$data['mode']='add';
$this->load->view('templates/template',$data);
}
else
{
$this -> invoice_model -> insert();
$this->flash->success('<h2> Details added Successfully!</h2>');
redirect('invoice');
}
}
Model:
function insert()
{
$data['total']=0;
$data['user'] = $this->input->post('user');
$data['ghi'] = ($this->input->post('ghi'))?$this->input->post('ghi'):0;
$data['abc'] = ($this->input->post('abc'))?$this->input->post('abc'):0;
$data['def'] = ($this->input->post('def'))?$this->input->post('def'):0;
$data['total'] = $data['ghi'] + $data['abc'] + $data['def'];
$data['freight_charges'] = $this->input->post('freight_charges');
$this->db->insert('invoice',$data);
}
View:
<script>
function showRequiredOption(cval)
{
if((cval=='interstate') || (cval == "stocktransfers"))
{
$('#ghi').hide();
$('#def').hide();
$('#abc').show();
}
else if ((cval=='exemptedsales') || (cval=="zeroratedsales") ||(cval=="jobwork"))
{
$('#ghi').hide();
$('#def').hide();
$('#abc').hide();
}
else
{
$('#abc').hide();
$('#ghi').show();
$('#def').show();
}
}
</script>
<div class="col-md-9 col-md-offset-2">
<div id="legend">
<legend class="">Profile Information</legend>
</div>
<form role="form" action="<?php echo site_url();?>invoice/addinvoice" method="post" class="form-horizontal" id="location" method="post" accept-charset="utf-8">
<div class="form-group">
<label class="control-label col-sm-2 " for="user">User</label>
<div class="col-sm-4 col-sm-offset-1">
<select id="user" name="user" onchange="showRequiredOption(this.value)">
<option value="employee">Local Sales</option>
<option value="interstate">Inter state</option>
<option value="stocktransfers">Stock transfers</option>
<option value="exemptedsales">Exempted Sales</option>
<option value="zeroratedcompany">Zero Rated Sales</option>
<option value="jobwork">Job Work</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2 " for="freight_charges">Freight Charges</label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control" id="freight_charges" name="freight_charges" value="<?php echo set_value('freight_charges');?>" />
</div>
</div>
<div class="form-group" id="abc" style="display:none;">
<label class="control-label col-sm-2 " for="abc">ABC</label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control" id="abc" name="abc" value="<?php echo set_value('abc');?>"/ >
</div>
</div>
<div class="form-group" id="def">
<label class="control-label col-sm-2 " for="def">DEF </label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control" id="def" name="def" value="<?php echo set_value('def');?>"/ >
</div>
</div>
<div class="form-group" id="ghi">
<label class="control-label col-sm-2 " for="ghi">GHI</label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control" id="ghi" name="ghi" value="<?php echo set_value('ghi');?>"/ >
</div>
</div>
<div class="form-group" id="cgst">
<label class="control-label col-sm-2 " for="total">Total</label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control" name="total" >
</div>
</div>
<button id="submit" type="submit" class="btn" name="submit">Submit</button>
</form>
</div>
Whatever values i have selected from dropdown only those values to be inserted into database and the rest of the values should be inserted as zero in the database.
Actually i am not getting how to do these can anyone check this.Thanks in Advance.
you should check for posted values in your php code as:
$total = 0;
if($this->input->post('this')){
$total = $this->input->post('this');//value in total
}
if($this->input->post('this2')){
$total += $this->input->post('this2');//value in total
}
and at the end send $total value in db as well.
in short php if else tags you can set variables like;
$this = ($this->input->post('this'))?$this->input->post('this'):0;
$this2 = ($this->input->post('this2'))?$this->input->post('this2'):0;
and then at the end you can make total of them and save them to database. OR as suggested above in comments that make your columns as DEFAULT 0 in your table.
------- IN YOUR CASE------
function insert()
{
$data['total']=0;
$data['user'] = $this->input->post('user');
$data['ghi'] = ($this->input->post('ghi'))?$this->input->post('ghi'):0;
$data['abc'] = ($this->input->post('abc'))?$this->input->post('abc'):0;
$data['def'] = ($this->input->post('def'))?$this->input->post('def'):0;
$data['total'] = $data['ghi'] + $data['abc'] + $data['def'];
$data['freight_charges'] = $this->input->post('freight_charges');
$this->db->insert('invoice',$data);
}
---------------IN JavaScript------------
on your event handler you can sum these by their IDs.
var total = parseInt($('#ghi').val())+parseInt($('#def').val());
and then show this total in your total div
$('#yourTotalDiv').text(total);
Displaying total amount on enter the details.
<script>
function showRequiredOption(cval)
{
if((cval=='interstate') || (cval == "stocktransfers"))
{
$('#ghi').hide();
$('#def').hide();
$('#abc').show();
}
else if ((cval=='exemptedsales') || (cval=="zeroratedsales") || (cval=="jobwork"))
{
$('#ghi').hide();
$('#def').hide();
$('#abc').hide();
}
else
{
$('#abc').hide();
$('#ghi').show();
$('#def').show();
}
}
</script>
<script>
$(document).ready(function(){
//iterate through each textboxes and add keyup
//handler to trigger sum event
$(".txt").each(function() {
$(this).keyup(function(){
calculateSum();
});
});
});
function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
$(".txt").each(function() {
//add only if the value is number
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseFloat(this.value);
}
});
//.toFixed() method will roundoff the final sum to 2 decimal places
$("#sum").html(sum.toFixed(2));
}
</script>
<div class="col-md-9 col-md-offset-2">
<div id="legend">
<legend class="">Profile Information</legend>
</div>
<form role="form" action="<?php echo site_url();?>invoice/addinvoice" method="post" class="form-horizontal" id="location" method="post" accept-charset="utf-8">
<div class="form-group">
<label class="control-label col-sm-2 " for="user">User</label>
<div class="col-sm-4 col-sm-offset-1">
<select id="user" name="user" onchange="showRequiredOption(this.value)">
<option value="employee">Local Sales</option>
<option value="interstate">Inter state</option>
<option value="stocktransfers">Stock transfers</option>
<option value="exemptedsales">Exempted Sales</option>
<option value="zeroratedcompany">Zero Rated Sales</option>
<option value="jobwork">Job Work</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2 " for="freight_charges">Freight Charges</label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control txt" id="freight_charges" name="freight_charges" value="<?php echo set_value('freight_charges');?>" />
</div>
</div>
<div class="form-group" id="abc" style="display:none;">
<label class="control-label col-sm-2 " for="abc">ABC</label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control txt" id="abc" name="abc" value="<?php echo set_value('abc');?>"/ >
</div>
</div>
<div class="form-group" id="def">
<label class="control-label col-sm-2 " for="def">DEF </label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control txt" id="def" name="def" value="<?php echo set_value('def');?>"/ >
</div>
</div>
<div class="form-group" id="ghi">
<label class="control-label col-sm-2 " for="ghi">GHI</label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control txt" id="ghi" name="ghi" value="<?php echo set_value('ghi');?>"/ >
</div>
</div>
<div class="form-group" id="summation">
<label class="control-label col-sm-2 " for="total">Total</label>
<div class="col-sm-4 col-sm-offset-1">
<span id="sum" class="form-control" type="text" name="total">0</span>
</div>
</div>
<button id="submit" type="submit" class="btn" name="submit">Submit</button>
</form>
</div>

How to upload image to database in php?

here i am trying to upload image to directory and add the path in database.
here i am first adding some product details and trying to upload the image to uploads directory and add the uploaded image path in database.
here is what i have done:
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "wan_products_box");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$product_name = mysqli_real_escape_string($link, $_POST['product_name']);
$product_category = mysqli_real_escape_string($link, $_POST['product_category']);
$product_price = mysqli_real_escape_string($link, $_POST['product_price']);
$pro_url = mysqli_real_escape_string($link, $_POST['pro_url']);
$co_owners = mysqli_real_escape_string($link, $_POST['co_owners']);
// attempt insert query execution
$sql = "INSERT INTO product_list (product_name, product_category, product_price,product_referrence_URL,product_co_owners) VALUES ('$product_name', '$product_category', '$product_price', '$pro_url', '$co_owners')";
if(mysqli_query($link, $sql)){
echo "New product created.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
//image upload code
if($_POST)
{
if($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
if(file_exists("uploaded_images/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
if(move_uploaded_file($_FILES["file"]["tmp_name"],"uploaded_images/" . $_FILES["file"]["name"]))
{
$query_image = "INSERT INTO product_list (product_image_url) values ('".$_FILES['file']['name']."')";
if(mysql_query($query_image))
{
echo "Stored in: " . "uploaded_images/" . $_FILES["file"]["name"];
}
else
{
echo 'Unable to store';
}
}
}
}
}
mysqli_close($link);
?>
this is my html form:
<div id="menu2" class="tab-pane fade">
<h4>Add new product</h4>
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
<div class="panel panel-default">
<div class="panel-body">
<form class="form-horizontal" method="post" action="files/insert.php" role="form">
<div class="form-group">
<label class="control-label col-sm-2" for="product_name">Product Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="product_name" id="product_name" placeholder="Iphone 5c" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="pwd">Product Category</label>
<div class="col-sm-10">
<select class="btn-btn-primary form-control" name="product_category">
<option>Mobile</option>
<option>Television</option>
<option>Printer</option>
<option>Watch</option>
<option>Monitor</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="product-pic">Upload your profile picture</label>
<div class="col-sm-10">
<input type="file" class="form-control" name="file" id="file" />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="product_price">Product Price</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="product_price" id="product_price" placeholder="Rs.36,000" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="pro_url">Reference URL</label>
<div class="col-sm-10">
<input type="URL" class="form-control" name="pro_url" id="pro_url" placeholder="http://www.amazon.com" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="co_owners">Co-owners</label>
<div class="col-sm-10">
<select class="btn-btn-primary form-control" name="co_owners">
<option>Select no. owners</option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
<option>7</option>
<option>8</option>
<option>9</option>
<option>10</option>
<option>11</option>
<option>12</option>
<option>13</option>
<option>14</option>
<option>15</option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-success">Add product</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
the data is inserted to database but the image upload part is not happening...
how can i do this? how can i modify the code to upload the image to database and add path to database?
when i run this the output i get is
New product created.
Notice: Undefined index: file in D:\xampp\htdocs\wan\files\insert.php on line 31
Notice: Undefined index: file in D:\xampp\htdocs\wan\files\insert.php on line 37
Notice: Undefined index: file in D:\xampp\htdocs\wan\files\insert.php on line 43
Notice: Undefined index: file in D:\xampp\htdocs\wan\files\insert.php on line
There are a few things wrong in your code.
Firstly, your form is missing a valid enctype enctype="multipart/form-data" it is required when dealing with files.
http://php.net/manual/en/features.file-upload.post-method.php
You're also mixing MySQL APIs in your second query.
$query_image = "INSERT INTO product_list (product_image_url) values ('".$_FILES['file']['name']."')";
if(mysql_query($query_image))
So it will fail.
Use the same method you used in your first query.
Those different APIs do not intermix.
So change that to if(mysqli_query($link, $query_image))
Also add or die(mysqli_error($link)) to mysqli_query() to check for errors.
Also make sure the folder has proper permissions to be written to.
Another thing, your <select>'s options have no values
<option>Select no. owners</option>
<option>1</option>
...
You need to add those
<option value="empty_value">Select no. owners</option>
<option value="1">1</option>
...
and do the same for the others.
Same thing for <option>Mobile</option>. There should be values for those too.
<option value="mobile">Mobile</option>
...
You will not get anything entered in your database for those.
Apart from the problems in HTML part like the lack of enctype="multipart/form-data". There is a problem in your second Query and this is the cause of these errors:
$query_image = "INSERT INTO product_list (product_image_url) values ('".$_FILES['file']['name']."')";
You need to change this to an UPDATE query and update the already created row in database.
Also it is a better approach to use the row's index number for the image name.

Categories