I want to show a message when the file has been uploaded, right below the UPDATE statement, but I'm struggling with the syntax. The full code:
if (empty($_FILES['image']['name']))
{
header('location:perfil.php?error=1');
return;
}
else if (!in_array($_FILES['image']['type'], $formatos))
{
header('location:perfil.php?error=2');
return;
}
else if (in_array($_FILES['image']['type'], $formatos))
{
if( mysqli_num_rows($todas_fotos) > 0) {
mysqli_query($conexao,"UPDATE esc_usuarios_fotos SET img_local = '$location' WHERE img_usu_codigo = '" . $_SESSION['codigo'] . "'");
if (move_uploaded_file($_FILES["image"]["tmp_name"],"images/perfis/" . $newFilename)){
header('location:perfil.php');
}
}
else {
mysqli_query($conexao,"insert into esc_usuarios_fotos (img_local, img_usu_codigo) values ('$location', '" . $_SESSION['codigo'] . "')");
}
header('location:perfil.php');
}
Any thoughts?
EDIT:
These are the upload parameters:
$fileinfo=PATHINFO($_FILES["image"]["name"]);
$newFilename=$fileinfo['filename'] ."_". time() . "." . $fileinfo['extension'];
move_uploaded_file($_FILES["image"]["tmp_name"],"images/perfis/" . $newFilename);
$location="images/perfis/" . $newFilename;
$todas_fotos = mysqli_query($conexao, "SELECT * FROM esc_usuarios_fotos WHERE
img_usu_codigo = '" . $_SESSION['codigo'] . "'");
$formatos = array('image/jpeg', 'image/png');/*
Related
Hellos.
Assist me with two queries in the file below intended to upload CSV files
Failing to upload to a MySQL without logging errors (Am I missing folder/file permissions?)
"Undefined offset" error from anything after column 10 in CSV (Is there a limit I declared unknowingly?)
Thank You.
if(isset($_POST['import'])){
$csvMimes = array('text/x-comma-separated-values',
'text/comma-separated-values',
'application/octet-stream',
'application/vnd.ms-excel',
'application/x-csv',
'text/x-csv', 'text/csv',
'application/csv',
'application/excel',
'application/vnd.msexcel',
'text/plain');
if(!empty($_FILES['file']['name'])
&& in_array($_FILES['file']['type'], $csvMimes))
{
if(is_uploaded_file($_FILES['file']['tmp_name'])){
$csvFile = fopen($_FILES['file']['tmp_name'], 'r');
fgetcsv($csvFile);
while(($line = fgetcsv($csvFile)) !== FALSE){
$ColID = $line[0];
$Col02 = $line[1];
$Col03 = $line[2];
$Col04 = $line[3];
$Col05 = $line[4];
$Col06 = $line[5];
$Col07 = $line[6];
$Col08 = $line[7];
$Col09 = $line[8];
$Col010 = $line[9];
$Col0n = $line[10];
$prevQuery = "SELECT id
FROM table_name
WHERE ColID = '".$line[0]."'";
$prevResult = $db->query($prevQuery);
if($prevResult){
if($prevResult->num_rows > 0){
$db->query("UPDATE table_name
SET ColHdg02 = '".$Col02."',
ColHdg03 = '".$Col03."',
ColHdg04 = '".$Col04."',
ColHdg05 = '".$Col05."',
ColHdg06 = '".$Col06."',
ColHdg07 = '".$Col07."',
ColHdg08 = '".$Col08."',
ColHdg09 = '".$Col09."',
ColHdg010 = '".$Col010."',
ColHdg0n = '".$Col0n."'
WHERE ColIDHdg = '".$ColID."'");
} else{
$db->query("INSERT INTO table_name
(ColIDHdg, ColHdg02, ColHdg03, ColHdg04,
ColHdg05, ColHdg06, ColHdg07, ColHdg08,
ColHdg09, ColHdg010, ColHdg0n)
VALUES ('".$ColID."', '".$Col02."', '".$Col03."',
'".$Col04."', '".$Col05."', '".$Col06."',
'".$Col07."', '".$Col08."', '".$Col09."',
'".$Col010."', '".$Col0n."')");
}
}
}
fclose($csvFile);
You're trying to get an Undefined offset, for your example please check if the number of items on $line is 11 or more.
if (count($line) > 10) {
$ColID = $line[0];
$Col02 = $line[1];
$Col03 = $line[2];
$Col04 = $line[3];
$Col05 = $line[4];
$Col06 = $line[5];
$Col07 = $line[6];
$Col08 = $line[7];
$Col09 = $line[8];
$Col010 = $line[9];
$Col0n = $line[10];
$prevQuery = "SELECT id FROM table_name WHERE ColID = '" . $line[0] . "'";
$prevResult = $db->query($prevQuery);
if ($prevResult) {
if ($prevResult->num_rows > 0) {
$db->query("UPDATE table_name SET ColHdg02 = '" . $Col02 . "', ColHdg03 = '" . $Col03 . "', ColHdg04 = '" . $Col04 . "', ColHdg05 = '" . $Col05 . "', ColHdg06 = '" . $Col06 . "', ColHdg07 = '" . $Col07 . "', ColHdg08 = '" . $Col08 . "', ColHdg09 = '" . $Col09 . "', ColHdg010 = '" . $Col010 . "', ColHdg0n = '" . $Col0n . "' WHERE ColIDHdg = '" . $ColID . "'");
} else {
$db->query("INSERT INTO table_name (ColIDHdg, ColHdg02, ColHdg03, ColHdg04, ColHdg05, ColHdg06, ColHdg07, ColHdg08, ColHdg09, ColHdg010, ColHdg0n) VALUES ('" . $ColID . "', '" . $Col02 . "', '" . $Col03 . "', '" . $Col04 . "', '" . $Col05 . "', '" . $Col06 . "', '" . $Col07 . "', '" . $Col08 . "', '" . $Col09 . "', '" . $Col010 . "', '" . $Col0n . "')");
}
}
}
The images are uploading normally, but I want an "else if" to check if there is any file selected. This is working:
<?php
session_start();
include('includes/conexao.php');
$fileinfo=PATHINFO($_FILES["image"]["name"]);
$newFilename=$fileinfo['filename'] ."_". time() . "." . $fileinfo['extension'];
move_uploaded_file($_FILES["image"]["tmp_name"],"images/perfis/" . $newFilename);
$location="images/perfis/" . $newFilename;
$todas_fotos = mysqli_query($conexao, "select * FROM esc_usuarios_fotos WHERE img_usu_codigo = '" . $_SESSION['codigo'] . "'");
if( mysqli_num_rows($todas_fotos) > 0) {
//$path=$location;
//if(unlink($path)) echo "Deleted file ";
mysqli_query($conexao,"UPDATE esc_usuarios_fotos SET img_local = '$location' WHERE img_usu_codigo = '" . $_SESSION['codigo'] . "'");
}
else if( mysqli_num_rows($todas_fotos) == 0)
{
mysqli_query($conexao,"insert into esc_usuarios_fotos (img_local, img_usu_codigo) values ('$location', '" . $_SESSION['codigo'] . "')");
}
else {
};
header('location:perfil.php');
?>
It inserts if there isn't an image, but if there is, it updates. But when I add:
else if (empty($_FILES['image']['name']))
{
header('location:perfil.php');
}
It returns me undefined index: extension on line 5. How to go?
Rewrite the code as follows. Here we are checking whether the file is not available at the beginning of the code and redirect if no file is found.
<?php
session_start();
if (empty($_FILES['image']['name']))
{
header('location:perfil.php?error=1');
return;
}
include('includes/conexao.php');
$fileinfo=PATHINFO($_FILES["image"]["name"]);
$newFilename=$fileinfo['filename'] ."_". time() . "." . $fileinfo['extension'];
move_uploaded_file($_FILES["image"]["tmp_name"],"images/perfis/" . $newFilename);
$location="images/perfis/" . $newFilename;
$todas_fotos = mysqli_query($conexao, "select * FROM esc_usuarios_fotos WHERE
img_usu_codigo = '" . $_SESSION['codigo'] . "'");
if( mysqli_num_rows($todas_fotos) > 0) {
//$path=$location;
//if(unlink($path)) echo "Deleted file ";
mysqli_query($conexao,"UPDATE esc_usuarios_fotos SET img_local = '$location' WHERE img_usu_codigo = '" . $_SESSION['codigo'] . "'");
}else {
mysqli_query($conexao,"insert into esc_usuarios_fotos (img_local, img_usu_codigo) values ('$location', '" . $_SESSION['codigo'] . "')");
}
and in the perfil.php you should put
window.onload = function(){
var url = new URL(window.location.href);
var error = url.searchParams.get("error");
if(error==1)
alert("No file uploaded");
}
This is my code
<?php
include "../../../config/config.php";
session_start();
if (isset($_GET['id'])) {
$id = $_GET['id'];
} else {
die("Not found");
}
if (isset($_POST['submit-edit'])) {
$title = mysqli_real_escape_string($con, $_POST['title']);
$description = mysqli_real_escape_string($con, $_POST['description']);
$category = mysqli_real_escape_string($con, $_POST['category']);
/* ----------------------- MAIN IMAGE -------------------------- */
$target_dir = "../../../img/find/thumbs-categorii/";
$target_file2 = "" . basename($_FILES["img-edit"]["name"]);
$target_file = $target_dir . basename($_FILES["img-edit"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file, PATHINFO_EXTENSION);
// Check file size
if ($_FILES["img-edit"]["size"] > 100000) {
$_SESSION['image-size'] = 1;
exit();
}
//
//Allow certain file formats
if ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" && $imageFileType != NULL) {
$_SESSION['image-format'] = 1;
exit();
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["img-edit"]["tmp_name"], $target_file)) {
} else {
echo "Sorry, there was an error uploading your file.";
// exit();
}
$query = "UPDATE descopera_second" .
"SET title='" . $title . "', text='" . $description . "', image='" .
$target_file2 . "', fk_descopera_first='" . $category .
"' WHERE id=" . $id;
var_dump($query);
exit();
$result = mysqli_query($con, $query);
// var_dump($query);
// exit();
if ($result) {
$_SESSION['edit_slider'] = 1;
header("Location: /dashboard/");
} else {
//
header("Location: /dashboard/");
}
}
}
?>
I want to keep the current path in database if the input with the image is empty. I don't know why, but my code currently stops at echo "Sorry, there was an error uploading your file."; and changes the path for the image, in my database. If the input is empty I want to keep the current path, because I just want to edit.
You define $uploadOk = 1, but that value never changes. So the following code, will always execute the else part of your condition.
if ($uploadOk == 0) {
} else {
/* Everything in here will be executed */
}
Now look at all of the code that inside of that one conditional block.
The first thing is another condition.
if (move_uploaded_file($_FILES["img-edit"]["tmp_name"], $target_file)) {
} else {
echo "Sorry, there was an error uploading your file.";
// exit();
}
Where you say your code is stopping means that move_uploaded_file failed. This would be expected if the user did not supply a file upload in the request. Because $target_file will be empty, and an empty string is probably not going to be a valid path on your filesystem, plus there's the fact that there was no file upload in the first place even if it were.
Everything else that happens inside that first conditional block then continues to happen anyway, unconditionally (i.e. updating your database even though there was no file uploaded).
$query = "UPDATE descopera_second" .
"SET title='" . $title . "', text='" . $description . "', image='" .
$target_file2 . "', fk_descopera_first='" . $category .
"' WHERE id=" . $id;
Try using var_dump to inspect the value of $target_file2 when this happens. It won't be what you expected. We know this because you initialize it as $target_file2 = "" . basename($_FILES["img-edit"]["name"]); above, and there was no file upload. So $_FILES is empty.
var_dump($target_file2);
So the better way to do this is to check if a valid file upload occurs first before attempting to update this value in your database. You probably meant to do this with your $uploadOk variable at the top.
if (isset($_FILES["img-edit"]["tmp_name"])) {
$query = "UPDATE descopera_second" .
"SET title='" . $title . "', text='" . $description . "', image='" .
$target_file2 . "', fk_descopera_first='" . $category .
"' WHERE id=" . $id;
} else {
$query = "UPDATE descopera_second" .
"SET title='" . $title . "', text='" . $description . "'," .
", fk_descopera_first='" . $category .
"' WHERE id=" . $id;
}
if (move_uploaded_file($_FILES["img-edit"]["tmp_name"], $target_dir)) {
I've created a page where I've place for updating the attachment. While doing so, if a file with same name, size, extension is attached, the attachment table need not be updated. This is the scenario. This is how I tried to do:
else if($mode == "attachment_update") {
$id = intval(mysqli_real_escape_string($mysqli, $_REQUEST["_id"]));
$upload_directory = "upload/attachment/";
$result = file_upload("attachment", "../".$upload_directory);
$file_name = '".addslashes($result[file_name])."';
write_log($file_name);
$file_extension = '".$result[file_extension]."';
write_log($file_extension);
$file_size = '".$result[file_size]."';
write_log($file_size);
$uploaded_file_name = '".$result[uploaded_file_name]."';
write_log($uploaded_file_name);
$uploaded_file_path = '".$upload_directory.$result[uploaded_file_name]."';
write_log($uploaded_file_path);
$query_select = "SELECT
file_name,
file_extension,
file_size,
uploaded_file_name,
uploaded_file_path
FROM
attachments
WHERE
id = 'id';";
$result1 = mysqli_query($mysqli, $query_select) or throwexception(mysqli_error($mysqli));
$row = mysqli_fetch_row($result1);
write_log($row[0]);
write_log($row[1]);
write_log($row[2]);
write_log($row[3]);
write_log($row[4]);
if($row[0] == $file_name &&
$row[1] == $file_extension &&
$row[2] == $file_size &&
$row[3] == $uploaded_file_name &&
$row[4] == $uploaded_file_path)
{
write_log("inside if");
} else {
if($result[status] == true) {
$query = "UPDATE
attachments
SET
file_name = '".addslashes($result[file_name])."',
file_extension = '".$result[file_extension]."',
file_size = '".$result[file_size]."',
uploaded_file_name = '".$result[uploaded_file_name]."',
uploaded_file_path = '".$upload_directory.$result[uploaded_file_name]."',
recorded_by = '$recorded_by',
recorded_datetime = '$recorded_datetime'
WHERE
id = 'id';";
mysqli_query($mysqli, $query) or throwexception(mysqli_error($mysqli));
}
}
echo json_encode(array("message" => "Updated successfully"));
exit;
}
The if condition does the thing. If all are true, the table will not be updated. If even any one fails, the table will be updated.
Here the problem is $file_name, $file_extension, $file_size, $uploaded_file_name are going null. I don't know how to retrieve it. Can someone tell how to retrieve those data, so that if can check it with the if condition?
In your case, You do not need to fire select query. just add AND condition in update query.
if ($mode == "attachment_update") {
$id = intval(mysqli_real_escape_string($mysqli, $_REQUEST["_id"]));
$upload_directory = "upload/attachment/";
$result = file_upload("attachment", "../" . $upload_directory);
$file_name = '".addslashes($result[file_name])."';
write_log($file_name);
$file_extension = '".$result[file_extension]."';
write_log($file_extension);
$file_size = '".$result[file_size]."';
write_log($file_size);
$uploaded_file_name = '".$result[uploaded_file_name]."';
write_log($uploaded_file_name);
$uploaded_file_path = '".$upload_directory.$result[uploaded_file_name]."';
write_log($uploaded_file_path);
$query = "UPDATE
attachments
SET
file_name = '" . addslashes($result[file_name]) . "',
file_extension = '" . $result[file_extension] . "',
file_size = '" . $result[file_size] . "',
uploaded_file_name = '" . $result[uploaded_file_name] . "',
uploaded_file_path = '" . $upload_directory . $result[uploaded_file_name] . "',
recorded_by = '$recorded_by',
recorded_datetime = '$recorded_datetime'
WHERE
id = 'id'
and file_name <> '" . addslashes($result[file_name]) . "',
and file_extension = '" . $result[file_extension] . "',
and file_size = '" . $result[file_size] . "',
and uploaded_file_name = '" . $result[uploaded_file_name] . "',
and uploaded_file_path = '" . $upload_directory . $result[uploaded_file_name] . "',
;";
mysqli_query($mysqli, $query) or throwexception(mysqli_error($mysqli));
echo json_encode(array("message" => "Updated successfully"));
exit;
}
Your question need more clarity.
Can you share the function,
$result = file_upload("attachment", "../".$upload_directory);
Are you able to log the values of $filename and $row?
write_log($file_name);
AND
write_log($row[0]);
Please tell me what could be the problem, can not get the variable order_id when the query is refreshed, if not specified, then all the request passes, but updates all records in the table, give advice where to look or what to read.
Thank you!
controller:
public function edit(){
if (isset($this->request->get['order_id'])) {
$order_id = $this->request->get['order_id'];
} else {
$order_id = 0;
}
if ($this->request->server['REQUEST_METHOD'] == 'POST') {
$this->model_account_order->update($order_id, $this->request->post);
$this->redirect($this->url->link('account/myorders', '', 'SSL'));
}
....
$this->data['action'] = $this->url->link('account/myorders/edite', '', 'SSL');
if (isset($this->request->get['order_id']) && ($this->request->server['REQUEST_METHOD'] != 'POST')) {
$edit_order = $this->model_account_order->getOrderData($this->request->get['order_id']);
}
if (isset($this->request->post['linkto'])) {
$this->data['linkto'] = $this->request->post['linkto'];
} elseif (isset($edit_order)) {
$this->data['linkto'] = $edit_order['linkto'];
} else {
$this->data['linkto'] = '';
}
if (isset($this->request->post['description'])) {
$this->data['description'] = $this->request->post['description'];
} elseif (isset($edit_order)) {
$this->data['description'] = $edit_order['description'];
} else {
$this->data['description'] = '';
}
Model:
public function update($order_id,$data){
$this->db->query("UPDATE " . DB_PREFIX . "order SET forma = '" . $this->db->escape($data['forma']) . "', linkto = '" . $this->db->escape($data['linkto']) . "', description = '" . $this->db->escape($data['description']) . "', cvet = '" . $this->db->escape($data['cvet']) . "', sizes = '" . (int)$data['sizes'] . "', counts = '" . (int)$data['counts'] . "', tcena = '" .(int)$data['tcena'] . "', sposob = '" . $this->db->escape($data['sposob']) . "' , delivery_usa = '" . $this->db->escape($data['delivery_usa']) . "', hint = '" . $this->db->escape($data['hint']) . "', novapochta ='" . $this->db->escape($data['novapochta']) . "' WHERE order_id = '" . (int)$order_id . "'");
}
Just very simple yet powerful solution - $order_id checking in the model:
public function update($order_id, $data) {
if (!$order_id) {
return false;
}
return $this->db->query("UPDATE " . DB_PREFIX . "order SET forma = '" . $this->db->escape($data['forma']) . "', linkto = '" . $this->db->escape($data['linkto']) . "', description = '" . $this->db->escape($data['description']) . "', cvet = '" . $this->db->escape($data['cvet']) . "', sizes = '" . (int)$data['sizes'] . "', counts = '" . (int)$data['counts'] . "', tcena = '" .(int)$data['tcena'] . "', sposob = '" . $this->db->escape($data['sposob']) . "' , delivery_usa = '" . $this->db->escape($data['delivery_usa']) . "', hint = '" . $this->db->escape($data['hint']) . "', novapochta ='" . $this->db->escape($data['novapochta']) . "' WHERE order_id = '" . (int)$order_id . "'");
}