php script upload only the first image to database - php

I have the form where you need to upload some pictures, but when I upload pictures in the uploader, only the first picture is saved.
I don't know where is the problem. Thank you so much for your time and help.
PHP
Here is the php script which is add picture to my database
session_start();
include '../../include/config.php';
// Create random name
function generateRandomString($length = 25) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
// Upload product image
$productimg = generateRandomString();
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["pimage"]["name"]);
$extension = end($temp);
$productimg = $productimg . "." . $extension;
move_uploaded_file($_FILES["pimage"]["tmp_name"],
"../../images/products/" . $productimg);
// Add product image
$sqlImage = "INSERT INTO productimages (pid, pimage) VALUES (" . $_REQUEST['pid'] . ",'" . $productimg . "')";
try{
$queryimg = $db->prepare($sqlImage);
$queryimg->execute();
}
catch(PDOException $ecop) {
die($ecop->getMessage());
}
//Select new default image
$sqlNewImage = "SELECT * FROM productimages WHERE pid=" . $_REQUEST['pid'];
try{
$query = $db->query($sqlNewImage);
$query->setFetchMode(PDO::FETCH_ASSOC);
$row = $query->fetch();
if ($query->rowCount() > 0) {
$newIMG = $row['pimage'];
}else
{
$newIMG = "default.png";
}
}
catch(PDOException $e) {
die($e->getMessage());
}
$sqlUpdateImage = "UPDATE products SET pimage = '" . $newIMG . "' WHERE id = " . $_REQUEST['pid'];
try{
$query = $db->prepare($sqlUpdateImage);
$query->execute();
}
catch(PDOException $e) {
die($e->getMessage());
}
$myUrl = "Location: ../index.php?p=edit&pid=" . $_REQUEST['pid'];
header($myUrl);
HTML
Here is the html code where is the form with function
<form action="functions/upload_image.php?pid=<?php echo $productid; ?>" method="post" class="form-horizontal" enctype="multipart/form-data" data-parsley-validate>
<div class="form-group">
<label for="cimage" class="control-label col-lg-4">Nahrát obrázek</label>
<div class="col-lg-8">
<input type="file" name="pimage" id="pimage" multiple="true"/>
</div>
</div>
<div class="form-group">
<center><button class="btn btn-lg btn-success" type="submit"><i class="fa fa-upload"></i> Nahrát</button></center>
</div>
</form>

Give the input an array-style name:
<input type="file" name="pimage" id="pimage[]" multiple="true"/>
Then all the entries in $_FILES['pimage'] will be arrays, and you can loop to insert them all.
$sqlImage = $db->prepare("INSERT INTO productimages (pid, pimage) VALUES (:pid, , :productimg)";
$sqlImage->bindParam(":pid", $_REQUEST['pid']);
$sqlImage->bindParam(":productimg", $productimg);
foreach ($_FILES['pimage']['name'] as $i => $name) {
$tmp_name = $_FILES['pimage']['tmp_name'][$i];
$temp = explode(".", $name);
$extension = end($temp);
$productimg = generateRandomString() . "." . $extension;
move_uploaded_file($temp_name, "../../images/products/" . $productimg);
try {
$sqlImage->execute();
} catch(PDOException $ecop) {
die($ecop->getMessage());
}
// .. similar code for other queries
}
Note also the use of bindParam() to prevent SQL injection.

Related

How to bind varying number of inputs when some are blob and must be sent send_long_data() in PHP

I am working on a school assignment and I need to process a form with values such as location, price, description, and a 1 to 4 images up to 5MB each. I need to upload to a database, but I cannot get the images sent using send_long_data(). I do not know how to process only some of the inputs as send long data. I have been able to cobble together code for binding an array of inputs by reference using call_user_func_array(), but for over a day now I have had no luck getting it to work. New to coding and I am stumped. Any help is appreciated.
**<?php
//show logged in/logout header
include 'header.php';
include 'connectLankasListDB.php';
$image_count = 0;
if(!isset($_SESSION['username'])) {
echo ('Please login before posting.');
sleep(2);
header('Location: login.html');
} elseif (empty($_POST['title']) or
empty($_POST['price']) or
empty($_POST['description']) or
empty($_POST['email']) or
empty($_POST['confirm_email'])) {
//All fields not filled out
echo 'Please fill out title, price, description, email, and email-confirmation fields.';
echo '<br/>';
echo 'New Post';
//email not a valid email, prompt to enter correct email
} elseif (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false) {
die("Enter a valid email address.");
//terms agreement checkbox not checked
} elseif ($_POST['terms'] === '0') {
die("Please agree to terms and conditions");
//email and confirmation email match, continue with script
} elseif ($_POST['email'] !== $_POST['confirm_email']) {
echo 'Email and confirmation email do not match--try again!';
//Check that image files are correct type and within the size limit
} elseif (isset($_FILES['images1'])) {
//print_r($_FILES);
$image_count = count(array_filter($_FILES['images1']['tmp_name'])); //number of uploaded images
$allowed_extensions = array("jpg", "jpeg", "png", "gif", "bmp");
for ($x=0; $x < $image_count; $x++) {
$file_name = $_FILES['images1']['name'][$x];
$file_size = $_FILES['images1']['size'][$x];
$file_tmp = $_FILES['images1']['tmp_name'];
//$ext = substr($file_name, strlen($file_name)-4,strlen($file_name));
$ext = explode(".", $file_name);
$file_ext = strtolower(end($ext));
echo $file_ext;
if (!in_array($file_ext, $allowed_extensions)) {
die("Only jpg, jpeg, png, gif, and bmp files allowed!");
} elseif ($file_size > 5000000) {
die("File size limit (5MB) exceed!");
}
}
}
//user has filled in all required fields
//validate and sanitize, store to variables
$sub_category = filter_input(INPUT_POST, 'sub_category', FILTER_SANITIZE_STRING);
$location = filter_input(INPUT_POST, 'location', FILTER_SANITIZE_STRING);
$title = filter_input(INPUT_POST, 'title', FILTER_SANITIZE_STRING);
$price = filter_input(INPUT_POST, 'price', FILTER_SANITIZE_NUMBER_FLOAT);
$description = filter_input(INPUT_POST, 'description', FILTER_SANITIZE_STRING);
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
$timestamp = date("Y-m-d H:i:s");
$terms = '1';
//retrieve Location_ID from Location table for Posts table
$sql1 = "SELECT Location_ID FROM Location WHERE LocationName = '$location'";
$query1 = mysqli_query($conn, $sql1) or die(mysqli_error($conn));
$result1 = mysqli_fetch_assoc($query1);
$location_id = $result1["Location_ID"];
//retrieve Subcategory_ID from SubCategory table for Posts table
$sql2 = "SELECT SubCategory_ID FROM SubCategory WHERE SubCategoryName = '$sub_category'";
$query2 = mysqli_query($conn, $sql2);
$result2 = mysqli_fetch_assoc($query2);
$subcategory_id = $result2["SubCategory_ID"];
/*
//save to Posts table
mysqli_query($conn, "INSERT INTO Posts
(Location_ID, title, price, description, email, SubCategory_ID, TimeStamp, Agreement)
VALUES
('" . $location_id . "', '" . $title . "', '" . $price . "', '". $description . "', '" . $email ."',"
. "'" . $subcategory_id ."', '" . $timestamp ."', '" . $terms . "')")
OR die(mysqli_error($conn));*/
**//query for insert with no images
$ins_query_fields = "Location_ID, Title, Price, Description, Email, SubCategory_ID,TimeStamp, Agreement";
$ins_query_vals = "?,?,?,?,?,?,?,?";
$type_args = "ssssssss";
$bind_vars = array($location_id, $title, $price, $description, $email, $subcategory_id, $timestamp, $terms);
$tmp_name_array = array();
$pic_name_array = array();
//print_r($_FILES['images1']['tmp_name']);
//prepare query based on number of images
if ($image_count > 0) {
$i = 1;
for($n = 0; $n < $image_count; $n++) {
$ins_query_fields .= ", Image_" . $i;
array_push($pic_name_array, "Image_". $i);
$ins_query_vals .= ",?";
$type_args .= "s";
${"Image_". $i} = $_FILES['images1']['tmp_name'][$n];
array_push($tmp_name_array, ${"Image_". $i});
$i++;
}
$bind_vars = array_merge($bind_vars, $tmp_name_array);
}
**//save image files to Posts table
///////////////////////////////////////
$stmt = $conn->prepare("INSERT INTO Posts($ins_query_fields) VALUES($ins_query_vals)");
//
//bind params by reference
$inputArray[] = &$type_args;
$j = count($bind_vars);
for($i=0; $i < $j; $i++) {
$inputArray[] = &$bind_vars[$i];
}
//print_r($inputArray);
//use call_user_func_array
call_user_func_array(array($stmt, 'bind_param'), $inputArray);
//$stmt->execute();
//print_r($bind_vars);
print_r($tmp_name_array);
if ($image_count > 0) {
$index = count($bind_vars) - $image_count - 1;
for($i = 0; $i < $image_count; $i++) {
$contents = $tmp_name_array[$i];
//$fp = fopen($bind_vars[($index) + $i], "r");
$fp = fopen($contents, "r");
$size = 0;
while ($data = fread($fp, 1024)) {
$size += strlen($data);
$stmt->send_long_data($index, $data);
}
}
}
if ($stmt->execute()) {
} else {
die($conn->error);
}****
echo 'Your post has been saved.<br/>';
echo '<br/>';
echo 'Go to Main Page';
?>**
Ok, I tried to separate the data upload, which is a fixed number of variables, and the image blob uploads, which i have tried doing with a loop. The first data posts, the images do not. Is this even workable this way? There must be some fundamental principle about this that I am not understanding. Here is the revised code, omitting the validation steps.
``if ($image_count > 0) {
$i = 1;
$pic_query_holder_x = "";
$tmp_name_array = array();
$pic_in_fields = array();
$pic_type_args = "";
for($n = 0; $n < $image_count; $n++) {
//$ins_query_fields .= ", Image_" . $i;
array_push($pic_in_fields, "Image_". $i);
$pic_query_holder_x .= ",?";
$pic_type_args .= "s";
${"Image_". $i} = $_FILES['images1']['tmp_name'][$n];
array_push($tmp_name_array, ${"Image_". $i});
$i++;
}
$pic_query_holder = ltrim($pic_query_holder_x, ',');
$pic_bind_vars = $tmp_name_array;
echo '<br/>';
echo $pic_query_holder;
echo '<br/>';
print_r($tmp_name_array);
}
//save image files to Posts table
///////////////////////////////////////
$stmt = $conn->prepare("INSERT INTO Posts($ins_query_fields)
VALUES($ins_query_vals)");
//
//bind params by reference
$inputArray[] = &$type_args;
$j = count($bind_vars);
for($i=0; $i < $j; $i++) {
$inputArray[] = &$bind_vars[$i];
}
//use call_user_func_array
call_user_func_array(array($stmt, 'bind_param'), $inputArray);
$stmt->execute();
//$index = count($bind_vars) - $image_count -1;
//$fp = fopen($tmp_name_array[$index], "r");
//$stmt->execute();
//print_r($pic_in_fields);
//print_r($pic_query_holder);
if ($image_count > 0) {
//bind params
$in_array[] = &$pic_type_args;
$k = count($tmp_name_array);
for ($i=0; $i < $k; $i++) {
$in_array[] = &$tmp_name_array[$i];
}
//$index = count($tmp_name_array) - $image_count - 1;
for($i = 0; $i < $image_count; $i++) {
//prepare statement
$go_pics = $conn->prepare("INSERT INTO Posts($pic_in_fields[$i]) VALUES(?)");
$contents = $tmp_name_array[$i];
//$fp = fopen($bind_vars[($index) + $i], "r");
$fs = fopen($contents, "r");
$size = 0;
while ($data = fread($fs, 1024)) {
$size += strlen($data);
$go_pics->send_long_data($i, $data);
}
//print_r($in_array);
$go_pics->execute();
}
}
enter code here
You can try tinker with this working template below. This uses send_long_data() to upload images to database. This adds a record with columns of different datatypes in just one query.
Didn't use call_user_func_array() as I don't think it's needed.
<?php
$conn = new mysqli("127.0.0.1", "root", "", "db");
if(isset($_POST['submit'])) {
$null1 = NULL;
$null2 = NULL;
$null3 = NULL;
$null4 = NULL;
$title = isset($_POST['title']) ? $_POST['title'] : '';
$email = isset($_POST['email']) ? $_POST['email'] : '';
$stmt = $conn->prepare("INSERT INTO Posts (Image_1, Image_2, Image_3, Image_4, title, email ) VALUES (?,?,?,?,?,?);");
$stmt->bind_param("bbbbss", $null1, $null2, $null3, $null4, $title, $email );
for($i = 0; $i < count( $_FILES['images1']['tmp_name'] ); $i++) {
if(!empty($_FILES['images1']['tmp_name'][$i])) {
$target_file = $_FILES['images1']['tmp_name'][$i];
$fp = fopen($target_file, "r");
while (!feof($fp)) {
$stmt->send_long_data($i, fread($fp, 8192));
}
fclose($fp);
unlink($_FILES['images1']['tmp_name'][$i]);
echo "Uploading image blob success!<br/>\n";
}
}
$stmt->execute();
$stmt->close();
$conn->close();
}
?>
<form action="" method="post" enctype="multipart/form-data">
<input type="text" name="title" value="this is the title"/><br/>
<input type="text" name="email" value="john#yahoo.com"/><br/>
<input type="file" name="images1[]" value=""/><br/>
<input type="file" name="images1[]" value=""/><br/>
<input type="file" name="images1[]" value=""/><br/>
<input type="file" name="images1[]" value=""/><br/><br/>
<input type="submit" name="submit" value="Upload Data"/>
</form>
<?php
$stmt = $mysqli->prepare("INSERT INTO messages (message) VALUES (?)");
$null = NULL;
$stmt->bind_param("b", $null);
$fp = fopen("messages.txt", "r");
while (!feof($fp)) {
$stmt->send_long_data(0, fread($fp, 8192));
}
fclose($fp);
$stmt->execute();
?>
This is straight from the PHP manual. Feof() is just there to ensure that the file exists and was opened properly. With a proper loop, you can access the image file and insert the blob into the database. Alternatively, you can prepare a series of blobs and do your database update or insert separately. Either way, I think this code should get you in the right direction.
Just run this segment to insert or update with blob data after you handle the non blobs.
Also, this SO page may help you too. Insert Blobs in MySql databases with php

how to save image in wordpress folder while using custom template

This is my code
$actual_name = pathinfo($filename,PATHINFO_FILENAME);
$original_name = $actual_name;
$extension = pathinfo($filename, PATHINFO_EXTENSION);
$filetype=$_FILES['file']['type'];
$target="../wp-content/themes/childtheme/img/";
if($filetype=='image/jpeg' or $filetype=='image/png' or
$filetype=='image/gif')
{
$i = 1;
while(file_exists($target.$actual_name.".".$extension)){
$actual_name = $original_name.$i;
$filename = $actual_name.".".$extension;
$i++;
}
$target = $target.basename( $filename ) ;
move_uploaded_file($_FILES['file']['tmp_name'],$target);
$insert="INSERT INTO EnterSchool(SliderImg ) VALUES('".$target."' )";
if (mysqli_query($db, $insert)) {
echo "saved ";
}
else {
echo "Error: " . $insert . "" . mysqli_error($db);
}
$db->close();
}}
html
<input type="file" name="file" id="file" >

How do i get the id of a submitted "new product" through my form, so i can rename an image submitted with it?

This is my code, and the image is uploaded where i want it to, but its named 0."file extension" everytime, but i want the image to have the same name as the id of the object im submitting with this form.
id: 3
img name: 3."file extension"
My php:
<?php
if (isset($_POST['submit_newProduct'])) { // Form has been submitted.
$errors = array();
// perform validations on the form data and avoid sql injection
$product_name = trim(mysqli_real_escape_string($connection, $_POST['product_name']));
$product_price = trim(mysqli_real_escape_string($connection, $_POST['product_price']));
$product_desc = trim(mysqli_real_escape_string($connection, $_POST['product_desc']));
$product_category = trim(mysqli_real_escape_string($connection, $_POST['product_category']));
$product_attribute = trim(mysqli_real_escape_string($connection, $_POST['product_attribute']));
$query = "INSERT INTO products
(product_name, product_price, product_desc,
product_category, product_attribute)
VALUES ('{$product_name}', '{$product_price}',
'{$product_desc}', '{$product_category}',
'{$product_attribute}')";
$filename = $_FILES["product_img"]["name"];
$file_basename = substr($filename, 0, strripos($filename, '.')); // get file extention
$file_ext = substr($filename, strripos($filename, '.')); // get file name
$filesize = $_FILES["product_img"]["size"];
$allowed_file_types = array('.png','.jpg','.jpeg','.gif');
if (in_array($file_ext,$allowed_file_types) && ($filesize < 200000)) {
// Rename file
$pid = mysqli_insert_id($connection);
$newfilename = $pid . $file_ext;
if (file_exists("img/product_img/" . $newfilename))
{
// file already exists error
echo "You have already uploaded this file.";
}
else
{
move_uploaded_file($_FILES["product_img"]["tmp_name"], "img/product_img/" . $newfilename);
echo "File uploaded successfully.";
}
}
elseif (empty($file_basename))
{
// file selection error
echo "Please select a file to upload.";
}
elseif ($filesize > 200000)
{
// file size error
echo "The file you are trying to upload is too large.";
}
else
{
// file type error
echo "Only these file typs are allowed for upload: " . implode(', ',$allowed_file_types);
unlink($_FILES["file"]["tmp_name"]);
}
header("location:product_list.php"); //maskes sure item is not recreated on refresh
$result = mysqli_query($connection, $query);
if ($result) {
$message = "Produkt oprettet.";
} else {
$message = "Der skete en fejl";
$message .= "<br />" . mysqli_error($connection);
}
}
?>
My html form:
<form action="" method="post" enctype="multipart/form-data">
<div class="col-md-6">
<h4>Produkt navn</h4>
<input type="text" name="product_name" class="form-control"> <br>
<h4>Produkt pris</h4>
<input type="text" placeholder="DKK" name="product_price" class="form-control" style="width:30%;"><br>
<h4>Produkt beskrivelse</h4>
<textarea type="text" name="product_desc" rows="3" class="form-control"></textarea> <br>
<h4>Produkt kategori</h4>
<select name="product_category" class="form-control">
<option></option>
<option>Gummi ænder</option>
<option>Påklædning</option>
<option>Accessories</option>
</select> <br>
<h4>Produkt attribut</h4>
<input type="text" name="product_attribute" class="form-control" value=""> <br>
<input type="file" name="product_img"><br>
<input type="submit" name="submit_newProduct" class="btn btn-warning pull-right" value="Tilføj produkt">
</div>
</form>
Since, Query is executing after mysqli_insert_id(); Thats why it is returning 0.
Place your query before mysqli_insert_id(), then only you will get inserted id.
I placed / edited your code in my way. You can change it accordingly.
<?php
if (isset($_POST['submit_newProduct'])) { // Form has been submitted.
$errors = array();
// perform validations on the form data and avoid sql injection
$product_name = trim(mysqli_real_escape_string($connection, $_POST['product_name']));
$product_price = trim(mysqli_real_escape_string($connection, $_POST['product_price']));
$product_desc = trim(mysqli_real_escape_string($connection, $_POST['product_desc']));
$product_category = trim(mysqli_real_escape_string($connection, $_POST['product_category']));
$product_attribute = trim(mysqli_real_escape_string($connection, $_POST['product_attribute']));
$query = "INSERT INTO products (product_name, product_price, product_desc, product_category, product_attribute)
VALUES ('{$product_name}', '{$product_price}', '{$product_desc}', '{$product_category}', '{$product_attribute}')";
$result = mysqli_query($connection, $query);
if ($result) {
$filename = $_FILES["product_img"]["name"];
$file_basename = substr($filename, 0, strripos($filename, '.')); // get file extention
$file_ext = substr($filename, strripos($filename, '.')); // get file name
$filesize = $_FILES["product_img"]["size"];
$allowed_file_types = array('.png','.jpg','.jpeg','.gif');
if (in_array($file_ext,$allowed_file_types) && ($filesize < 200000)) {
// Rename file
$pid = mysqli_insert_id($connection);
$newfilename = $pid . $file_ext;
if (file_exists("img/product_img/" . $newfilename)){
// file already exists error
echo "You have already uploaded this file.";
} else {
move_uploaded_file($_FILES["product_img"]["tmp_name"], "img/product_img/" . $newfilename);
echo "File uploaded successfully.";
}
}
elseif (empty($file_basename)){
// file selection error
echo "Please select a file to upload.";
}
elseif ($filesize > 200000){
// file size error
echo "The file you are trying to upload is too large.";
}
else{
// file type error
echo "Only these file typs are allowed for upload: " . implode(', ',$allowed_file_types);
unlink($_FILES["file"]["tmp_name"]);
}
$message = "Produkt oprettet.";
}
else {
$message = "Der skete en fejl";
$message .= "<br />" . mysqli_error($connection);
}
header("location:product_list.php"); //maskes sure item is not recreated on refresh
}
?>

Script for multiple image upload doesn't work properly

I trying to make script which upload multiple images into folder on server and save name and some other info in database. The script is working fine until I tried to add parameters to save type, size and category. I I remove this 3 lines below it is working.
$fileSize = $_FILES['user_files']['size'];
$fileType = $_FILES['user_files']['type'];
$album = $_POST['image_album'];
This is the script and I would like someone to help me with this.
if (isset($_POST["sub2"])) {
// include resized library
require_once('php-image-magician/php_image_magician.php');
$msg = "";
$valid_image_check = array("image/gif", "image/jpeg", "image/jpg", "image/png", "image/bmp");
if (count($_FILES["user_files"]) > 0) {
$folderName = "uploads/";
$sql = "INSERT INTO images (image_name, image_size, image_type, image_album) VALUES (:img, :size, :type, :album)";
$stmt = $pdo->prepare($sql);
for ($i = 0; $i < count($_FILES["user_files"]["name"]); $i++) {
if ($_FILES["user_files"]["name"][$i] <> "") {
$image_mime = strtolower(image_type_to_mime_type(exif_imagetype($_FILES["user_files"]["tmp_name"][$i])));
// if valid image type then upload
if (in_array($image_mime, $valid_image_check)) {
$ext = explode("/", strtolower($image_mime));
$ext = strtolower(end($ext));
$filename = rand(10000, 990000) . '_' . time() . '.' . $ext;
$filepath = $folderName . $filename;
$fileSize = $_FILES['user_files']['size']; <---- // THIS
$fileType = $_FILES['user_files']['type']; // THIS
$album = $_POST['image_album']; // AND THIS
if (!move_uploaded_file($_FILES["user_files"]["tmp_name"][$i], $filepath)) {
$emsg .= "Error while uploading - <strong>" . $_FILES["user_files"]["name"][$i] . "</strong><br>";
$counter++;
} else {
$smsg .= "Image <strong>" . $_FILES["user_files"]["name"][$i] . "</strong> is added. <br>";
$magicianObj = new imageLib($filepath);
$magicianObj->resizeImage(100, 100);
$magicianObj->saveImage($folderName . 'thumb/' . $filename, 100);
/* * ****** insert into database starts ******** */
try {
$stmt->bindValue(":img", $filename);
$stmt->bindValue(":size", $fileSize);
$stmt->bindValue(":type", $fileType);
$stmt->bindValue(":album", $album);
$stmt->execute();
$result = $stmt->rowCount();
if ($result > 0) {
// file uplaoded successfully.
} else {
// failed to insert into database.
}
} catch (Exception $ex) {
$emsg .= "<strong>" . $ex->getMessage() . "</strong>. <br>";
}
/* * ****** insert into database ends ******** */
}
} else {
$emsg .= "This file <strong>" . $_FILES["user_files"]["name"][$i] . "</strong> isn't image. <br>";
}
}
}
And this is the form
<form name="f2" action="" method="post" enctype="multipart/form-data">
<fieldset>
Album
<select name="image_album">
<option value="1">Album 1</option>
<option value="2">Album 2</option>
<option value="3" >Album 3</option>
<option value="4" >Album 4</option>
<option value="5">Album 5</option>
</select>
<input class="files" name="user_files[]" type="file" ><span><a href="javascript:void(0);" class="add" >Add more</a></span>
<div><input type="submit" class="submit" name="sub2" value="Качи" /> </div>
</fieldset>
</form>

Upload CSV into database using php

I am working on a little project of mine and I came to the conclusion that being able to automatically upload a excel sheet to my database would be very, very useful,the problem is that I don´t have an idea of where to start, I have researched a bit and decieded to use a CSV file created from a excel sheet to upload the data into the table of my DB.
Most of the examples I have seem look like a mess with the PHP code into the html instead of dividing the logic in different files like what I have been doing in this last 2 months.
What I have right now is the upload form in html:
<form enctype="multipart/form-data" method="post" id="uploadForm">
<input name="filesfiles" id="upload" type="file" accept=".csv" class="left" />
<input type="submit" value="Cargar" />
</form>
And a small sample of how the CSV file looks in text:
Cedula;Nombre;Apellido1;Apellido2;Correo;IdRol;Estado
1657890;Dominico;Scarlatti;Viera;leetrills#yahoo.com;2;0
5657890;Franz;Listz;Linerman;flizts#hotmail.com;3;0
Or in some other excel versions:
Cedula,Nombre,Primer Apellido,Segundo Apellido,Correo,IDRol,Estado
126548791,Franz ,Ritter ,von Liszt,fliszt#arppegio.com,3,0
174657109,Sofia ,Asgatovna ,Gubaidulina ,gubaidulina#yahoo.com,3,0
The first row is the name of the columns (which should be ignored when adding the info) of the table I want to upload the file into.
The problem is that I don´t know how to link the upload file once the submit button is clicked to a PHP code in my includes that inserts the CSV into the table.
Thanks a lot in advance
EDIT:
JSFiddle of the upload form
EDIT4:
I am a stroke of pure genius and skill Maduka was able to help me solve this behemoth of problem. I can't thank him enough, the following is the code used in hopes that it may serve someone someday and save them the grief of failure.
<?php
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_WARNING & ~E_STRICT);
mysql_connect('localhost', 'root', '');
mysql_select_db("proyecto") or die(mysql_error());
if (isset($_FILES['csvupload'])) {
$errors = array();
$allowed_ext = array('.csv');
$file_name = $_FILES['csvupload']['name'];
$file_ext = strtolower(end(explode('.', $file_name)));
$file_size = $_FILES['csvupload']['size'];
$file_tmp = $_FILES['csvupload']['tmp_name'];
if (in_array($allowed_ext) === false) {
$errors[] = 'La extensión del archivo no es valida.';
}
if ($file_size > 10485760) {
$errors[] = 'El archivo sobrepasa el limite de 10MB';
}
if (empty($errors)) {
$handle = fopen($file_tmp, "r");
while (!feof($handle)) {
$value = (fgetcsv($handle, 0, ','));
if ($i > 0) {
if ($value[0] != '') {
$inserts[] = "('" . mysql_real_escape_string($value[0]) . "','"
. mysql_real_escape_string($value["1"]) . "','"
. mysql_real_escape_string($value["2"]) . "','"
. mysql_real_escape_string($value["3"]) . "','"
. mysql_real_escape_string($value["4"]) . "','"
. mysql_real_escape_string($value["5"]) . "','"
. mysql_real_escape_string($value["6"]) . "')";
}
} elseif ($i == 0) {
$fields = $value;
}
$i++;
}
mysql_query("INSERT INTO `usuarios` (`cedula`,`nombre`,`apellido1`,`apellido2`,`correo`,`idRol`,`estado`) VALUES " . implode(",", $inserts));
fclose($handle);
if ($sq1) {
echo '¡Los usuarios han sido agregados exitosamente!';
}
}
}
?>
Here is the basic code which you need to do your task,
$file = fopen($_FILES['csvUpload']['tmp_name'], "r");
$i = 0;
while (!feof($file)) {
$value = (fgetcsv($file, 0, ';'));
if ($i > 0) {
if ($value[0] != '') {
$inserts[] = "(" . $value[0] . ","
. $value["1"] . ","
. $value["2"] . ","
. $value["3"] . ","
. $value["4"] . ","
. $value["5"] . ","
. $value["6"] . ")";
}
} elseif ($i == 0) {
$fields = $value;
}
$i++;
}
mysql_query("INSERT INTO `MyTable` (`" . $fields[0] . "`,`" . $fields[1] . "`,`" . $fields[2] . "`,`" . $fields[3] . "`,`" . $fields[4] . "`,`" . $fields[5] . "`) VALUES " . implode(",", $inserts));
fclose($file);
You have to implement validation, check file type and size limit. Then insert your data to the table. I have use MySQL bulk insert to handle large amount of data. Hope this helps!
EDIT 1:
Please replace your code with this code and see if it is working correctly.
<?php
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_WARNING);
mysql_connect('localhost', 'root', '');
mysql_select_db("proyecto") or die(mysql_error());
if (isset($_FILES['csvUpload'])) {
$errors = array();
$allowed_ext = array('.csv');
$file_name = $_FILES['csvUpload']['name'];
$file_ext = strtolower(end(explode('.', $file_name)));
$file_size = $_FILES['csvUpload']['size'];
$file_tmp = $_FILES['csvUpload']['tmp_name'];
if (in_array($allowed_ext) === false) {
$errors[] = 'La extensión del archivo no es valida.';
}
if ($file_size > 10485760) {
$errors[] = 'El archivo sobrepasa el limite de 10MB';
}
if (empty($errors)) {
$handle = fopen($file_tmp, "r");
while (($fileop = fgetcsv($handle, ";") && fgetcsv($handle, ",")) !== false) {
$cedula = mysql_real_escape_string($fileop[0]);
$nombre = mysql_real_escape_string($fileop[2]);
$apellido1 = mysql_real_escape_string($fileop[3]);
$apellido2 = mysql_real_escape_string($fileop[4]);
$correo = mysql_real_escape_string($fileop[5]);
$idRol = mysql_real_escape_string($fileop[6]);
$estado = mysql_real_escape_string($fileop[9]);
$sq1 = mysql_query("INSERT INTO `usuarios` (cedula,nombre,apellido1,apellido2,correo,idRol,estado) VALUES ('$cedula','$nombre','$apellido1','$apellido2','$correo','$idRol','$estado')");
}
fclose($handle);
if ($sq1) {
echo '¡Los usuarios han sido agregados exitosamente!';
}
}
}
?>
<form enctype="multipart/form-data" method="post" id="uploadForm">
<input name="csvUpload" id="upload" type="file" accept=".csv" class="left" />
<input type="submit" value="¡Cargar!" />
</form>
Upload form
<form enctype="multipart/form-data" action="uploader.php" method="POST">
<ul><li>
<input name="file" type="file" /><br /></li><li>
<br><input type="submit" name="submit" value="Upload" /></li>
</ul>
</form>
uploader.php
<?php
if (isset($_FILES['file'])) {
$errors = array();
$allowed_ext = array('csv');
$file_name = $_FILES['file']['name'];
$file_ext = strtolower(end(explode('.', $file_name)));
$file_size = $_FILES['file']['size'];
$file_tmp = $_FILES['file']['tmp_name'];
if (in_array($file_ext, $allowed_ext) === false) {
$errors[] ='Extension not allowed';
}
if ($file_size > 10485760) {
$errors[] = 'File size must be under 10mb';
}
if (empty($errors)) {
$handle = fopen($file_tmp,"r");
while(($fileop = fgetcsv($handle,",")) !== false)
{
$companycode = mysql_real_escape_string($fileop[0]);
$pdtcode = mysql_real_escape_string($fileop[2]);
$Item = mysql_real_escape_string($fileop[3]);
$pack = preg_replace('/[^A-Za-z0-9\. -]/', '', $fileop[4]);
$lastmonth = mysql_real_escape_string($fileop[5]);
$ltlmonth = mysql_real_escape_string($fileop[6]);
$op = mysql_real_escape_string($fileop[9]);
$pur = mysql_real_escape_string($fileop[10]);
$sale = mysql_real_escape_string($fileop[12]);
$bal = mysql_real_escape_string($fileop[17]);
$bval = mysql_real_escape_string($fileop[18]);
$sval = mysql_real_escape_string($fileop[19]);
$sq1 = mysql_query("INSERT INTO `sas` (companycode,pdtcode,Item,pack,lastmonth,ltlmonth,op,pur,sale,bal,bval,sval) VALUES ('$companycode','$pdtcode','$Item','$pack','$lastmonth','$ltlmonth','$op','$pur','$sale','$bal','$bval','$sval')");
}
fclose($handle);
if($sq1){
echo 'Stock and Sales successfully updated. Please check the values.<br><br>';
}
}
?>
The above code is simple. I am using for my project.

Categories