uploading image not working with running querys using foreach - php

i am strcuked in a unexpected problem..i am having many queries of creating and insert.
eg:
if (isset($_POST['install']))
{
$install_queries[] = "CREATE TABLE..............";
$install_queries[] = "CREATE TABLE..............";
$install_queries[] = "CREATE TABLE..............";
$allowedExtss = array("jpg", "jpeg", "png");
$extensions = end(explode(".", $_FILES["path2"]["name"]));
//echo $extension;
if (($extensions == "jpeg")|| ($extensions == "jpg")|| ($extensions == "png"))
{
if ($_FILES["path2"]["error"] > 0)
{
$msgs = $_FILES["path2"]["error"] . "<br />";
}
else
{
move_uploaded_file($_FILES["path2"]["tmp_name"],
"../images/" . $_FILES["path2"]["name"]);
}
$filename2 = "images/" . $_FILES["path2"]["name"]; }
$install_queries[] = "INSERT INTO TABLE(image) VALUES('$filename2')";
foreach ($install_queries as $q)
{
//running queries here
}
but on ruuning script it is inserting it with blank in image filed..but another fields are filled...............
Thanks

Is it uploading any images at all?
Perhaps only insert into the image table if the upload is successful.
if (isset($_POST['install']))
{
$install_queries[] = "CREATE TABLE..............";
$install_queries[] = "CREATE TABLE..............";
$install_queries[] = "CREATE TABLE..............";
$allowedExtss = array("jpg", "jpeg", "png");
$extensions = end(explode(".", $_FILES["path2"]["name"]));
//echo $extension;
if (($extensions == "jpeg")|| ($extensions == "jpg")|| ($extensions == "png"))
{
if ($_FILES["path2"]["error"] > 0)
{
$msgs = $_FILES["path2"]["error"] . "<br />";
}
else
{
if(move_uploaded_file($_FILES["path2"]["tmp_name"],
"../images/" . $_FILES["path2"]["name"])) {
$filename2 = "images/" . $_FILES["path2"]["name"];
$install_queries[] = "INSERT INTO `image` VALUES('$filename2')";
}
}
foreach ($install_queries as $q)
{
//running queries here
}

Related

Stop uploading file if encountered an error on a block of if else statements

Is there any way to check if there will be an error on file uploading? Like putting a variable to know if there's an error on every else statement so that before it will prevent running the query. Because what's happening is even there's an error on moving/copying/deleting a file, it still runs the query.
$dir = './uploads/images/';
if ($_FILES['thumbnail']['size'] == 0 && $_FILES['thumbnail']['error'] > 0){
$new_path = $dir;
$new_file = $new_path . $exist_tn;
$move = rename($cur_file,$new_file);
if ($move) {
$thumbnail = $exist_tn;
} else {
echo "Error Moving File.";
}
}else{
$thumbnail = $thumb;
$deletefile = unlink($cur_file);
if($deletefile){
$targetPath = $dir.$thumbnail;
$sourcePath = $_FILES['thumbnail']['tmp_name'];
$movefile = move_uploaded_file($sourcePath,$targetPath);
if ($movefile) {
echo "File upload successfully.";
}else{
echo "Upload File Failed.";
}
}else{
echo "Delete File failed.";
}
}
$query = '
UPDATE
`mytbl`
SET
`title` = "'.$title.'",
`thumbnail` ="'.$thumbnail.'",
`date` = "'.$date.'",
`part` = "'.$part.'",
`tags`= "'.$tags.'"
WHERE
`id` = "'.$id.'"
';
$update = mysqli_query(db(),$query);
//Check if there's an error first then run query
if (checkCondition) {
if($update === TRUE){
echo "sql_update";
}else{
echo "sql_error";
}
} else {
echo "Error Found";
}
Use exit after echo if you don't want the query to run
e.g
$dir = './uploads/images/';
if ($_FILES['thumbnail']['size'] == 0 && $_FILES['thumbnail']['error'] > 0){
$new_path = $dir;
$new_file = $new_path . $exist_tn;
$move = rename($cur_file,$new_file);
if ($move) {
$thumbnail = $exist_tn;
} else {
echo "Error Moving File.";
exit();
}
}else{
$thumbnail = $thumb;
$deletefile = unlink($cur_file);
if($deletefile){
$targetPath = $dir.$thumbnail;
$sourcePath = $_FILES['thumbnail']['tmp_name'];
$movefile = move_uploaded_file($sourcePath,$targetPath);
if ($movefile) {
echo "File upload successfully.";
}else{
echo "Upload File Failed.";
exit();
}
}else{
echo "Delete File failed.";
exit();
}
}
$query = '
UPDATE
`mytbl`
SET
`title` = "'.$title.'",
`thumbnail` ="'.$thumbnail.'",
`date` = "'.$date.'",
`part` = "'.$part.'",
`tags`= "'.$tags.'"
WHERE
`id` = "'.$id.'"
';
$update = mysqli_query(db(),$query);
//Check if there's an error first then run query
if (checkCondition) {
if($update === TRUE){
echo "sql_update";
}else{
echo "sql_error";
}
} else {
echo "Error Found";
}

Write each uploaded file name to SQL database (PHP, MySQL)

I'm a PHP beginner and i managed to muscle up a code which has a person upload up to 4 documents to a designated folder on a server. I'm now having trouble writing code which takes these 4 document names and adds them to that person's column with the rest of input data. I believe the right approach is to go with a "foreach" loop which increments variable name every time it goes through uploaded file names. I've tried doing this with $documentname[$i] = $file_name; but it's not working.
This is what I have so far:
$upload_dir = 'uploads/';
$allowed_types = array(
'doc',
'docx'
);
$maxsize = 4 * 1024 * 1024;
if (!empty(array_filter($_FILES['files']['name']))) {
// var_dump($_FILES);
// die();
$i=1;
foreach ($_FILES['files']['tmp_name'] as $key => $value) {
$file_tmpname = $_FILES['files']['tmp_name'][$key];
$file_name = $_FILES['files']['name'][$key];
$file_size = $_FILES['files']['size'][$key];
$file_ext = pathinfo($file_name, PATHINFO_EXTENSION);
$filepath = $location . $file_name;
$documentname[$i] = $file_name;
if (in_array(strtolower($file_ext), $allowed_types)) {
if ($file_size > $maxsize)
echo "Greška, datoteke su veće od dozvoljene vrijednosti (4MB)";
if (file_exists($filepath)) {
$filepath = $location . time() . $file_name;
if (move_uploaded_file($file_tmpname, $filepath)) {
echo "{$file_name} uspješno uploadan <br />";
} else {
echo "Error uploading {$file_name} <br />";
}
} else {
if (move_uploaded_file($file_tmpname, $filepath)) {
echo "{$file_name} uspješno uploadan <br />";
} else {
echo "Error uploading {$file_name} <br />";
}
}
} else {
// If file extention not valid
echo "Error uploading {$file_name} ";
echo "({$file_ext} file type is not allowed)<br / >";
}
}
} else {
// If no files selected
echo "No files selected.";
}}
And this is the sql code:
if (isset($_POST['signup'])) {
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$documentname1 = $_POST['documentname1'];
$documentname2 = $_POST['documentname2'];
$documentname3 = $_POST['documentname3'];
$documentname4 = $_POST['documentname4'];
$msg = mysqli_query($con, "insert into users(fname,lname,documentname1,documentname2,documentname3,documentname4)
values('$fname','$lname','$documentname1','$documentname2','$documentname3','$documentname4')");
So the question is: is it possible to iterate through the uploaded files name array and assign each file name a variable like #documentname1,#documentname2,... to write these names in the database?
Thank you in advance!
Change your code to look like this. And also use prepared statement - PDO
if (isset($_POST['signup'])) {
$upload_dir = 'uploads/';
$allowed_types = array(
'doc',
'docx'
);
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$countfiles = count($_FILES['files']['name']);
$doc_name = [];
$maxsize = 4 * 1024 * 1024;
if (!empty(array_filter($_FILES['files']['name']))) {
// var_dump($_FILES);
// die();
for ($i=0;$i<$countfiles;$i++) {
$file_tmpname = $_FILES['files']['tmp_name'][$i];
$file_name = $_FILES['files']['name'][$i];
$file_size = $_FILES['files']['size'][$i];
$file_ext = pathinfo($file_name, PATHINFO_EXTENSION);
$filepath = $location . $file_name;
$doc_name[] += $_FILES['files']['name'][$i];
if (in_array(strtolower($file_ext), $allowed_types)) {
if ($file_size > $maxsize)
$error[] = "Greška, datoteke su veće od dozvoljene vrijednosti (4MB)";
if (file_exists($filepath)) {
$filepath = $location . time() . $file_name;
if (move_uploaded_file($file_tmpname, $filepath)) {
$success[] = "{$file_name} uspješno uploadan <br />";
} else {
$error[] = "Error uploading {$file_name} <br />";
}
}
} else {
// If file extention not valid
$error[] = "Error uploading {$file_name} ";
$error[] = "({$file_ext} file type is not allowed)<br / >";
}
}
} else {
// If no files selected
$error[] = "No files selected.";
}}
if (!isset($error)) {
$documentname1 = $doc_name[0]
$documentname2 = $doc_name[1]
$documentname3 = $doc_name[2]
$documentname4 = $doc_name[3]
$msg = mysqli_query($con, "insert into users(fname,lname,documentname1,documentname2,documentname3,documentname4)
values('$fname','$lname','$documentname1','$documentname2','$documentname3','$documentname4')");
}
}
to show errors on your html
if(isset($error)){
foreach($error as $error){
echo '<div class="alert alert-danger" role="alert">
<button class="close" data-dismiss="alert"></button>' .$error.'<br /> </div>';
}
}
to show success
if(isset($success)){
foreach($success as $success){
echo '<div class="alert alert-success" role="alert">
<button class="close" data-dismiss="alert"></button>' .$success.'<br /> </div>';
}
}

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" >

PHP multiple image store record to database

I made a code for multiple image uploader, but just first image is stored to mysql table and both into path, some help?
This is my code:
if(!empty($_FILES['file'])){
foreach($_FILES['file']['name'] as $key => $name){
if($_FILES['file']['error'][$key] == 0){
$temp = $_FILES['file']['tmp_name'][$key];
$ext = explode('.', $name);
$ext = strtolower(end($ext));
$file = md5_file($temp) . time() . '.' . $ext;
if(in_array($ext, $allowed) === true && move_uploaded_file($temp, "product_images/{$file}") === true){
$path = 'product_images';
mysql_query("INSERT INTO `products` (img_path, img_name) VALUES ('$path', '$file')");
}else{
$errors[] = 'Format slike mora biti .jpg ili .png';
}
}
}
}

PHP - How to import 200k data faster? And there's 403 error

How can I import 200k data faster?
And when I importing csv (delimited by comma) file using online, I got 403 error, and it inserted 200-400 data only. Also when I try to import it using localhost (xampp) i got
"Exception EAccessViolation in module xampp-control.exe at 001AA712.
Access violation at address 005AA712 in module 'xampp-control.exe'.
Read of address 00000042"
And the SQL Database connection is gone.
This is the code I used.
set_time_limit(0);
ignore_user_abort(true);
$file = $_FILES['file']['name'];
$type = $_FILES['file']['type'];
$size = $_FILES['file']['size'];
$temp = $_FILES['file']['tmp_name'];
$error = $_FILES['file']['error'];
if( ! $file)
{
$data['error'] = "Please select a file!";
}
else if($type != "application/vnd.ms-excel" && $type != "application/octet-stream")
{
$data['error'] = "Invalid file type!";
}
else
{
$newname = $file." - ".date("Ymd His");
move_uploaded_file($temp, "uploads/".$newname);
$fieldseparator = ",";
$lineseparator = "\n";
$csvfile = "uploads/".$newname;
if( ! file_exists($csvfile))
{
echo "File not found. Make sure you specified the correct path.\n";
exit;
}
$file = fopen($csvfile,"r");
if( ! $file)
{
echo "Error opening data file.";
exit;
}
$size = filesize($csvfile);
if(!$size)
{
echo "File is empty.";
exit;
}
$csvcontent = fread($file,$size);
fclose($file);
$row = 1;
$data_imported = 0;
$file3 = fopen($csvfile,"r");
$total_file_count = (count(file(FCPATH."/".$csvfile)) - 2);
$i = 0;
$insert = "INSERT IGNORE INTO `invoice`
(`row1`,
.
.
to
.
.
`row33`
) VALUES ";
while($datas = fgetcsv($file3, 10000, ","))
{
$i++;
ob_implicit_flush(true);
if($row == 1)
{
// Ignore 1st line
}
else
{
$row1 = isset($datas[0]) ? $datas[0] : "";
.
.
to
.
.
$row33 = isset($datas[32]) ? $datas[32] : "";
if($i == 200 OR $total_file_count == $data_imported)
{
$insert .= "(
'".mysqli_real_escape_string($this->db->conn_id(),$row1)."',
.
.
to
.
.
'".mysqli_real_escape_string($this->db->conn_id(),$row33)."'
);";
}
else
{
$insert .= "(
'".mysqli_real_escape_string($this->db->conn_id(),$row1)."',
.
.
to
.
.
'".mysqli_real_escape_string($this->db->conn_id(),$row33)."'
),";
}
if($i == 200 OR $total_file_count == $data_imported)
{
$this->QModel->query($insert);
$i=0;
$insert = "INSERT IGNORE INTO `invoice`
(`row1`,
.
.
to
.
.
`row33`
) VALUES ";
}
$data_imported++;
}
$row++;
}
fclose($file3);
echo "Success imported ".number_format($data_imported)." data.";
Any ideas?
Thank you.

Categories