I was trying to make a website where image can be uploaded to the database and be edited on the website like replacing the image. Whenever I try to replace the picture in the website, it gets replaced in the database but it doesn't show up in the website.
This is my PhP code.
if(isset($_POST['update_post'])){
$post_author = $_POST['post_author'];
$post_title = $_POST['post_title'];
// post_category from input
$post_category_id = $_POST['post_category'];
$post_status = $_POST['post_status'];
$post_image = $_FILES['post_image']['name'];
$post_image_temp = $_FILES['post_image']['name'];
$post_content = $_POST['post_content'];
$post_tags = $_POST['post_tags'];
move_uploaded_file($post_image_temp, "../images/$post_image");
if(empty($post_image)) {
$query = "SELECT * FROM posts WHERE post_id = $the_post_id ";
$select_image = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($select_image)){
$post_image = $row['post_image'];
}
}
$query = "UPDATE posts SET ";
$query .= "post_title = '{$post_title}', ";
$query .= "post_category_id = '{$post_category_id}', ";
$query .= "post_date = now(), ";
$query .= "post_author = '{$post_author}', ";
$query .= "post_status = '{$post_status}', ";
$query .= "post_tags = '{$post_tags}', ";
$query .= "post_content = '{$post_content}', ";
$query .= "post_image = '{$post_image}' ";
$query .= "WHERE post_id = {$the_post_id} ";
$update_query = mysqli_query($connection, $query);
confirm($update_query);
}
This the my database
Database Image
This is my website
Website Image
As you can see in the database, I have the images there but in my website, some pictures are not showing up. I want all of them to show up. Please help
I am uploading multiple images to my sql database but my implode method isn't working...
if(isset($_POST['submit'])) {
$id = $_POST['id'];
for($i = 0; $i < count($_FILES['file_upload']['name']); $i++){
$filetmp = $_FILES['file_upload']['tmp_name'][$i];
$filename = basename($_FILES['file_upload']['name'][$i]);
$filetype = $_FILES['file_upload']['type'][$i];
$filepath = "../images/".$filename;
move_uploaded_file($filetmp,$filepath);
}
$mainfiles = implode(", ", $filename);
$sql = "INSERT INTO pictures2 (";
$sql .= "image, photograph_id";
$sql .= ") VALUES ('";
$sql .= $database->escape_character($mainfiles) ."', '";
$sql .= $id ."')";
$result = $database->query($sql);
if($result){
$session->message('<div class="success-msg">Pictures uploaded sucessfully.</div>');
}
}
$filename should be an array. You are passing string into implode function. Do something like this.
if(isset($_POST['submit'])) {
$id = $_POST['id'];
$filename= [];
for($i = 0; $i < count($_FILES['file_upload']['name']); $i++){
$filetmp = $_FILES['file_upload']['tmp_name'][$i];
$filename[] = basename($_FILES['file_upload']['name'][$i]);
$filetype = $_FILES['file_upload']['type'][$i];
$filepath = "../images/".$filename[$i];
move_uploaded_file($filetmp,$filepath);
}
$mainfiles = implode(", ", $filename);
$sql = "INSERT INTO pictures2 (";
$sql .= "image, photograph_id";
$sql .= ") VALUES ('";
$sql .= $database->escape_character($mainfiles) ."', '";
$sql .= $id ."')";
$result = $database->query($sql);
if($result){
$session->message('<div class="success-msg">Pictures uploaded sucessfully.</div>');
}
}
Hope this helps.
Made changes like this, I am considering $id is your photograph_id
if (isset($_POST['submit'])) {
$id = $_POST['id'];
for ($i = 0; $i < count($_FILES['file_upload']['name']); $i++) {
$filetmp = $_FILES['file_upload']['tmp_name'][$i];
$filename[] = [$id, basename($_FILES['file_upload']['name'][$i])]; // here changes
$filetype = $_FILES['file_upload']['type'][$i];
$filepath = "../images/" . $filename;
move_uploaded_file($filetmp, $filepath);
}
// I made changes at below code
$valueStr = array_map(function ($item) {
return "('" . implode("','", $item) . "'),"; // to convert into `,` separated values
}, $filename);
$mainfiles = rtrim(implode("", $valueStr), ','); // removing right training `,`
$sql = "INSERT INTO pictures2 (";
$sql .= "image, photograph_id";
$sql .= ") VALUES ('";
$sql .= $database->escape_character($mainfiles) . "', '";
$sql .= $id . "')";
$result = $database->query($sql);
if ($result) {
$session->message('<div class="success-msg">Pictures uploaded sucessfully.</div>');
}
}
I have the following problem, I send a JSON to a PHP service
(the staff that was responsible for PHP is no longer in the company) that inserts the JSON data into the database.
The problem is that the way the PHP page is developed it returns me that the data was entered even when they are not! I need it, when something goes wrong, to show me what happened (why the insert was not done) so I can fix it.
What should I change on the PHP page so it can satisfy the question I mentioned?
This is the page
<?php
$startTime = microtime(true);
include_once("../utils/config.php");
include_once("../utils/utils.php");
include_once("../services/rest.utils.php");
function reviewAluno($aluno) {
$aluno->nome = quoteOrNull($aluno->nome);
$aluno->rm = quoteOrNull($aluno->rm);
$aluno->rg = quoteOrNull($aluno->rg);
$aluno->usuario = quoteOrNull($aluno->usuario);
$aluno->senha = quoteOrNull($aluno->senha);
$aluno->cursoAluno = quoteOrNull($aluno->cursoAluno);
$aluno->urlFoto = quoteOrNull($aluno->urlFoto);
$aluno->email = quoteOrNull($aluno->email);
$aluno->rgEscolar = quoteOrNull($aluno->rgEscolar);
$aluno->cpf = quoteOrNull($aluno->cpf);
$aluno->naturalidade = quoteOrNull($aluno->naturalidade);
$aluno->nacionalidade = quoteOrNull($aluno->nacionalidade);
$aluno->dataNascimento = formataDataIsoToMySQL($aluno->dataNascimento);
$aluno->endereco = quoteOrNull($aluno->endereco);
$aluno->numero = quoteOrNull($aluno->numero);
$aluno->complemento = quoteOrNull($aluno->complemento);
$aluno->bairro = quoteOrNull($aluno->bairro);
$aluno->cep = quoteOrNull($aluno->cep);
$aluno->cidade = quoteOrNull($aluno->cidade);
$aluno->estado = quoteOrNull($aluno->estado);
$aluno->pais = quoteOrNull($aluno->pais);
$aluno->telefone = quoteOrNull($aluno->telefone);
$aluno->telefoneResidencial = quoteOrNull($aluno->telefoneResidencial);
$aluno->telefoneCelular = quoteOrNull($aluno->telefoneCelular);
$aluno->certidaoNumero = quoteOrNull($aluno->certidaoNumero);
$aluno->certidaoFolha = quoteOrNull($aluno->certidaoFolha);
$aluno->certidaoLivro = quoteOrNull($aluno->certidaoLivro);
$aluno->certidaoDistrito = quoteOrNull($aluno->certidaoDistrito);
$aluno->certidaoCidade = quoteOrNull($aluno->certidaoCidade);
$aluno->certidaoEstado = quoteOrNull($aluno->certidaoEstado);
$aluno->certidaoEmissao = formataDataIsoToMySQL($aluno->certidaoEmissao);
$aluno->certidaoHash = quoteOrNull($aluno->certidaoHash);
$aluno->rgOrgao = quoteOrNull($aluno->rgOrgao);
$aluno->rgDataEmissao = formataDataIsoToMySQL($aluno->rgDataEmissao);
$aluno->religiao = quoteOrNull($aluno->religiao);
$aluno->catraca = quoteOrNull($aluno->catraca);
$aluno->trabalhoEmpresa = quoteOrNull($aluno->trabalhoEmpresa);
$aluno->trabalhoTelefone = quoteOrNull($aluno->trabalhoTelefone);
$aluno->medicamento1 = quoteOrNull($aluno->medicamento1);
$aluno->medicamento2 = quoteOrNull($aluno->medicamento2);
$aluno->medicamento3 = quoteOrNull($aluno->medicamento3);
$aluno->medicamento4 = quoteOrNull($aluno->medicamento4);
$aluno->alergia = quoteOrNull($aluno->alergia);
$aluno->disturbioVisual = quoteOrNull($aluno->disturbioVisual);
$aluno->disturbioAuditivo = quoteOrNull($aluno->disturbioAuditivo);
$aluno->hospital = quoteOrNull($aluno->hospital);
$aluno->medicoPessoal = quoteOrNull($aluno->medicoPessoal);
$aluno->planoSaude = quoteOrNull($aluno->planoSaude);
$aluno->restricaoAlimentar = quoteOrNull($aluno->restricaoAlimentar);
$aluno->observacoesSaude = quoteOrNull($aluno->observacoesSaude);
$aluno->tituloEleitor = quoteOrNull($aluno->tituloEleitor);
$aluno->certificadoMilitar = quoteOrNull($aluno->certificadoMilitar);
$aluno->estadoCivil = quoteOrNull($aluno->estadoCivil);
$aluno->escolaMedio = quoteOrNull($aluno->escolaMedio);
$aluno->escolaCidade = quoteOrNull($aluno->escolaCidade);
$aluno->escolaEstado = quoteOrNull($aluno->escolaEstado);
$aluno->escolaAno = quoteOrNull($aluno->escolaAno);
$aluno->dataFalecimento = formataDataIsoToMySQL($aluno->dataFalecimento);
$aluno->contrato = quoteOrNull($aluno->contrato);
$aluno->ultimaAtualizacao = formataDataIsoToMySQL($aluno->ultimaAtualizacao);
$aluno->ultimaPublicacao = formataDataIsoToMySQL($aluno->ultimaPublicacao);
$aluno->autoRespLegal = quoteOrNull($aluno->autoRespLegal);
$aluno->autoRespFinan = quoteOrNull($aluno->autoRespFinan);
$aluno->podeFamiliares = quoteOrNull($aluno->podeFamiliares);
$aluno->podeSozinho = quoteOrNull($aluno->podeSozinho);
$aluno->podeSozinhoExtra = quoteOrNull($aluno->podeSozinhoExtra);
$aluno->podeEsperarFora = quoteOrNull($aluno->podeEsperarFora);
$aluno->validadeAcesso = formataDataIsoToMySQL($aluno->validadeAcesso);
}
$body = trim(file_get_contents('php://input'));
$list = carregaCorpo($body);
if (signatureCheck($body)) {
$tableAluno = getTabela("Aluno");
$cta = 0;
$database = conectaDatabase();
$script = '';
foreach ($list as $aluno) {
reviewAluno($aluno);
$sqlDelete = "DELETE FROM {$tableAluno} WHERE alunoID = {$aluno->alunoID};";
$sqlInsert = "INSERT INTO {$tableAluno} ";
$sqlInsert .= '(alunoID, nome, rm, rg, usuario, senha, cursoAluno, urlFoto, email, ';
$sqlInsert .= ' rgEscolar, cpf, naturalidade, nacionalidade, sexo, raca, dataNascimento, ';
$sqlInsert .= ' endereco, numero, complemento, bairro, cep, cidade, estado, pais, ';
$sqlInsert .= ' telefone, telefoneResidencial, telefoneCelular, certidaoNumero, certidaoFolha, ';
$sqlInsert .= ' certidaoLivro, certidaoDistrito, certidaoCidade, certidaoEstado, ';
$sqlInsert .= ' certidaoEmissao, certidaoHash, rgOrgao, rgDataEmissao, religiao, ';
$sqlInsert .= ' catraca, trabalhoEmpresa, trabalhoTelefone,';
$sqlInsert .= ' medicamento1, medicamento2, medicamento3, ';
$sqlInsert .= ' medicamento4, alergia, desmaio, vacinas, disturbioVisual, ';
$sqlInsert .= ' disturbioAuditivo, acidente, hospital, medicoPessoal, planoSaude, ';
$sqlInsert .= ' restricaoAlimentar, observacoesSaude, tituloEleitor, certificadoMilitar, ';
$sqlInsert .= ' estadoCivil, escolaMedio, escolaCidade, escolaEstado, escolaAno, ';
$sqlInsert .= ' dataFalecimento, contrato, ultimaAtualizacao, ultimaPublicacao, ';
$sqlInsert .= ' autoRespLegal, autoRespFinan, podeFamiliares, podeSozinho, ';
$sqlInsert .= ' podeSozinhoExtra, podeEsperarFora, validadeAcesso) ';
$sqlInsert .= ' VALUES ( ';
$sqlInsert .= " {$aluno->alunoID}, {$aluno->nome}, {$aluno->rm}, {$aluno->rg}, {$aluno->usuario}, ";
$sqlInsert .= " {$aluno->senha}, {$aluno->cursoAluno}, {$aluno->urlFoto}, {$aluno->email}, ";
$sqlInsert .= " {$aluno->rgEscolar}, {$aluno->cpf}, {$aluno->naturalidade}, {$aluno->nacionalidade}, ";
$sqlInsert .= " {$aluno->sexo}, {$aluno->raca}, {$aluno->dataNascimento}, {$aluno->endereco}, ";
$sqlInsert .= " {$aluno->numero}, {$aluno->complemento}, {$aluno->bairro}, {$aluno->cep}, ";
$sqlInsert .= " {$aluno->cidade}, {$aluno->estado}, {$aluno->pais}, {$aluno->telefone}, ";
$sqlInsert .= " {$aluno->telefoneResidencial}, {$aluno->telefoneCelular}, {$aluno->certidaoNumero}, {$aluno->certidaoFolha}, ";
$sqlInsert .= " {$aluno->certidaoLivro}, {$aluno->certidaoDistrito}, {$aluno->certidaoCidade}, {$aluno->certidaoEstado}, ";
$sqlInsert .= " {$aluno->certidaoEmissao}, {$aluno->certidaoHash}, {$aluno->rgOrgao}, {$aluno->rgDataEmissao}, ";
$sqlInsert .= " {$aluno->religiao}, {$aluno->catraca}, {$aluno->trabalhoEmpresa}, {$aluno->trabalhoTelefone}, ";
$sqlInsert .= " {$aluno->medicamento1}, {$aluno->medicamento2}, ";
$sqlInsert .= " {$aluno->medicamento3}, {$aluno->medicamento4}, {$aluno->alergia}, {$aluno->desmaio}, ";
$sqlInsert .= " {$aluno->vacinas}, {$aluno->disturbioVisual}, {$aluno->disturbioAuditivo}, {$aluno->acidente}, ";
$sqlInsert .= " {$aluno->hospital}, {$aluno->medicoPessoal}, {$aluno->planoSaude}, {$aluno->restricaoAlimentar}, ";
$sqlInsert .= " {$aluno->observacoesSaude}, {$aluno->tituloEleitor}, {$aluno->certificadoMilitar}, {$aluno->estadoCivil}, ";
$sqlInsert .= " {$aluno->escolaMedio}, {$aluno->escolaCidade}, {$aluno->escolaEstado}, {$aluno->escolaAno}, ";
$sqlInsert .= " {$aluno->dataFalecimento}, {$aluno->contrato}, {$aluno->ultimaAtualizacao}, ";
$sqlInsert .= " {$aluno->ultimaPublicacao}, {$aluno->autoRespLegal}, {$aluno->autoRespFinan}, ";
$sqlInsert .= " {$aluno->podeFamiliares}, {$aluno->podeSozinho}, {$aluno->podeSozinhoExtra}, ";
$sqlInsert .= " {$aluno->podeEsperarFora}, {$aluno->validadeAcesso} ";
$sqlInsert .= ");";
sqlExecute($database, $sqlDelete);
sqlExecute($database, $sqlInsert);
$script .= $sqlDelete . "\n";
$script .= $sqlInsert . "\n";
$cta++;
}
desconectaDB($database);
$description = "{$cta} alunos foram registrados";
$status = "200";
salvaScript($script, 'alunos');
} else {
$description = "não autorizado";
$status = "401";
}
$endTime = microtime(true);
$timeSpent = $endTime - $startTime;
echo "{\"status\":{$status}, \"descricao\":\"$description\", \"timeSpent\": \"{$timeSpent}\"}";
Find the code that defines function sqlExecute() (I'm guessing it's in utils.php) and the line where it runs mysql_query() (just a guess; there are now several better ways to do this but this code looks ancient so that's what it probably does).
Make sure that sqlExecute() returns the return value of mysql_query(), which is a boolean for success.
Save the outcome of both queries in a variable:
$success = sqlExecute($database, $sqlDelete);
$success = $success && sqlExecute($database, $sqlInsert);
Then use $success in an if condition to decide whether to return the JSON for "success" or a different JSON message for "error".
(Sidenote: This entire script is a horror show, and should ideally be thrown away and rewritten, but that's a different topic.)
I cannot get my two file upload fields working with my update form. I'm able to get create_form to upload the files to my server and input info into the SQL database, but I can't get the edit to take without receiving an error. Files don't upload and info doesn't update in SQL. Please help!
<?php require_once($_SERVER['DOCUMENT_ROOT']."/includes/session.php");?>
<?php require_once($_SERVER['DOCUMENT_ROOT']."/includes/db_connection.php");?>
<?php
session_start();
if($_SESSION["login_user"] != true) {
echo("Access denied!");
exit();
}
?>
<?php require_once($_SERVER['DOCUMENT_ROOT']."/includes/functions.php");?>
<?php require_once($_SERVER['DOCUMENT_ROOT']."/includes/validation_functions.php");?>
<?php find_selected_event_page(); ?>
<?php
if (!$current_event) {
// page ID was missing or invalid or
// page couldn't be found in database
redirect_to("manage_content.php");
}
?>
<?php
if (isset($_POST['submit'])) {
// Process the form
// validations
$required_fields = array("visible");
validate_presences($required_fields);
if (empty($errors)) {
// Perform Update
$id = $current_event["id"];
$visible = mysql_prep($_POST["visible"]);
$homepage = mysql_prep($_POST["homepage"]);
$fa_id = mysql_prep($_POST["fa_id"]);
$title = mysql_prep($_POST["title"]);
$caption = mysql_prep($_POST["caption"]);
$url = mysql_prep($_POST["url"]);
$month = mysql_prep($_POST["month"]);
$date = mysql_prep($_POST["date"]);
$year = mysql_prep($_POST["year"]);
$summary = mysql_prep($_POST["summary"]);
$full_text = mysql_prep($_POST["full_text"]);
$image = rand(1000,100000)."-".$_FILES['image']['name'];
$image_loc = $_FILES['image']['tmp_name'];
$image_size = $_FILES['image']['size'];
$image_type = $_FILES['image']['type'];
$image_folder="images/";
$file = rand(1000,100000)."-".$_FILES['file']['name'];
$file_loc = $_FILES['file']['tmp_name'];
$file_size = $_FILES['file']['size'];
$file_type = $_FILES['file']['type'];
$file_folder="files/";
$final_image=str_replace(' ','-',$new_image_name);
$final_file=str_replace(' ','-',$new_file_name);
if($_FILES) {
unlink("images/".$current_event['image']);
move_uploaded_file($image_loc,$image_folder.$final_image);
unlink("files/".$current_event['file']);
move_uploaded_file($file_loc,$file_folder.$final_file); }
else
{
// if no image selected the old image remain as it is.
$final_image = $current_event['image']; // old image from database
$fine_file = $current_event['file']; // old image from database
}
$query = "UPDATE `events` SET ";
$query .= "`visible` = '{$visible}', ";
$query .= "`homepage` = '{$homepage}', ";
$query .= "`fa_id` = '{$fa_id}', ";
$query .= "`title` = '{$title}', ";
$query .= "`caption` = '{$caption}', ";
$query .= "`url` = '{$url}', ";
$query .= "`month` = '{$month}', ";
$query .= "`date` = '{$date}', ";
$query .= "`year` = '{$year}', ";
$query .= "`summary` = '{$summary}', ";
$query .= "`full_text` = '{$full_text}', ";
$query .= "`image` = '{$final_image}', ";
$query .= "`image_type` = '{$image_type}', ";
$query .= "`image_size` = '{$image_new_size}' ";
$query .= "`file` = '{$final_file}', ";
$query .= "`file_type` = '{$file_type}', ";
$query .= "`file_size` = '{$file_new_size}' ";
$query .= "WHERE `events`.`id` = {$id} ";
$query .= "LIMIT 1";
$result = mysqli_query($connection, $query);
if ($result && mysqli_affected_rows($connection)) {
// Success
echo "<pre>".$query."</pre>";
$_SESSION["message"] = "Item updated.";
redirect_to("manage_content.php");
} else {
// Failure
//$_SESSION["message"] = "Item creation failed.";
//redirect_to("new_news.php");
echo "Error: " . $query . "<br>" . $result->error;
}
}
} else {
// This is probably a GET request
} // end: if (isset($_POST['submit']))
?>
Here is the error:
Error: UPDATE events SET visible = 'Y', homepage = 'Y', fa_id = '460463', title = 'Event', caption = 'Event Caption', url = '', month = '1', date = '', year = '2017', summary = 'Support event.', full_text = 'Join event', image = '', image_type = '', image_size = '' file = '', file_type = '', file_size = '' WHERE events.id = 1 LIMIT 1
Somebody solve my problem. Update query not work.
Error in Update query this step... Array to string conversion $query .= "image = '{$image}' "; ------------------------------------------------------------------------------------------------------------------------------------
if (isset($_POST['submit'])) {
$file = rand(1000,100000)."-".$_FILES['image']['name'];
$file_loc = $_FILES['image']['tmp_name'];
$folder="uploads/";
$new_file_name = strtolower($file);
$image =str_replace(' ','-',$new_file_name);
move_uploaded_file($file_loc,$folder.$image);
$firstname = $_POST["firstname"];
$lastname = $_POST["lastname"];
$address1 = $_POST["address1"];
$address2 = $_POST["address2"];
$city = $_POST["city"];
$state = $_POST["state"];
$zipcode = $_POST["zipcode"];
$email = $_POST["email"];
$country = $_POST["country"];
$phone = $_POST["phone"];
$image = $_FILES["image"];
$username = $_POST["username"];
$passwordold = $_POST["oldpassword"];
$passwordone = $_POST["passwordone"];
$passwordtwo = $_POST["passwordtwo"];
$sessions = $_SESSION['admin_id'];
$query = "UPDATE user SET ";
$query .= "firstname = '{$firstname}', ";
$query .= "lastname = '{$lastname}', ";
$query .= "addressone = '{$address1}', ";
$query .= "addresstwo = '{$address2}', ";
$query .= "city = '{$city}', ";
$query .= "state = '{$state}', ";
$query .= "zipcode = '{$zipcode}', ";
$query .= "email = '{$email}', ";
$query .= "country = '{$country}', ";
$query .= "phone = '{$phone}', ";
$query .= "image = {$image} ";
$query .= "WHERE id = {$sessions} ";
$query .= "LIMIT 1";
$result = mysqli_query($connection, $query);
echo "<pre>";
print_r($_FILES);
print_r($_POST);
echo "</pre>";
}
$_FILES["image"] is an array. You can only pass string in sql queries. May be you need to serialize the array and then store it in the database.