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.
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" >
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
}
?>
Please am trying to upload docs, .docx, .pdf, .jpg files using php but each time I click on the upload button, I get this message: "uploadedFile format not supported! uploaded".
Please where is the problem coming from? It is supposed to be either 'uploaded' or 'file format not supported'.
Thanks.
<?php
require_once "include/db_handle.php";
if (isset($_POST['upload'])) {
if (!empty($_FILES['_file']['name'])) {
if ($_FILES['_file']['type'] == 'application/msword') {
$upload_folder = "./file_doc/";
$pic_name = time() . ".doc";
$pic_path = $upload_folder . $pic_name;
move_uploaded_file($_FILES['_file']['tmp_name'], $pic_path);
$upload = "INSERT INTO tfiles (name) VALUES ('$pic_name')";
if ($db->query($upload)) {
echo "uploaded";
}
}
if ($_FILES['_file']['type'] == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document') {
$upload_folder = "./file_doc/";
$pic_name = time() . ".doc";
$pic_path = $upload_folder . $pic_name;
move_uploaded_file($_FILES['_file']['tmp_name'], $pic_path);
$upload = "INSERT INTO tfiles (name) VALUES ('$pic_name')";
if ($db->query($upload)) {
echo "uploaded";
}
}
if ($_FILES['_file']['type'] == 'application/pdf') {
$upload_folder = "./file_doc/";
$pic_name = time() . ".pdf";
$pic_path = $upload_folder . $pic_name;
move_uploaded_file($_FILES['_file']['tmp_name'], $pic_path);
$upload = "INSERT INTO tfiles (name) VALUES ('$pic_name')";
if ($db->query($upload)) {
echo "uploaded";
}
}
if ($_FILES['_file']['type'] == 'application/vnd.openxmlformats-officedocument.presentationml.presentation') {
$upload_folder = "./file_doc/";
$pic_name = time() . ".pptx";
$pic_path = $upload_folder . $pic_name;
move_uploaded_file($_FILES['_file']['tmp_name'], $pic_path);
$upload = "INSERT INTO tfiles (name) VALUES ('$pic_name')";
if ($db->query($upload)) {
echo "uploaded";
}
}
if ($_FILES['_file']['type'] == 'image/jpeg') {
$upload_folder = "./profile_pix/";
$pic_name = time() . ".jpg";
$pic_path = $upload_folder . $pic_name;
require_once "include/resize.php";
if (move_uploaded_file($_FILES['_file']['tmp_name'], $pic_path)) {
$image = new Resize($pic_path);
$image->resizeImage(180, 180, 'crop');
$image->saveImage($pic_path);
//thumbnail
$image = new Resize($pic_path);
$image->resizeImage(50, 50, 'crop');
$image->saveImage($upload_folder . "thumb/" . $pic_name);
}
$upload = "INSERT INTO tfiles (name) VALUES ('$pic_name')";
if ($db->query($upload)) {
echo "uploaded";
}
}
else{
echo "File format not supported!";
}
}
}
?>
HTML Form
<p class="points" > Add Files</p>
<form name="" action="" method="post" enctype="multipart/form-data">
<input type="file" name= "_file" />
<input type= "submit" name="upload" value="upload"/>
</form>
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.