Get INSERT return on response - php

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.)

Related

phpqrcode how to implement

I am trying to update my codes by saving the data with QR Code.
I tried to implement this tutorial, but It is not saving the QR Code, after I submit the form the page just keeps loading, it only saves the data from the form without the QR Code.
Any help?
this is how I added the udate
include"phpqrcode/qrlib.php";
$folderTemp = 'assets/img/';
$c = $a;
$qrimage = $a.".png";
$qual = 'H';
$ukuran = 6;
$padding = 0;
QRCode :: png($c,$folderTemp.$qrimage,$qual,$ukuran,$padding);
function save_register(){
extract($_POST);
$data = " event_id = '$event_id' ";
$data .= ", name = '$name' ";
$data .= ", address = '$address' ";
$data .= ", email = '$email' ";
$data .= ", contact = '$contact' ";
$data .= ", pacote = '$pacote' ";
$data .= ", qrimage = '$qrimage' ";
if(isset($status))
$data .= ", status = '$status' ";
if(isset($payment_status))
$data .= ", payment_status = '$payment_status' ";
else
$data .= ", payment_status = '0' ";
if(empty($id)){
$save = $this->db->query("INSERT INTO audience set ".$data);
}else{
$save = $this->db->query("UPDATE audience set ".$data." where id=".$id);
}
if($save)
return 1;
}

How to implode image file names into mysql database

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>');
}
}

Error trying to run a multiqyery

Sorry if its a little mistake. i was using first time multi query. error 1 and error 2 both codes are same except single colon('') added in error 2 insert row. if i echo from inside the the for loop shows everything fine. some time success but not inserted in data base. Thank You in advance.
Error 1: Error :You have an error in your SQL syntax; check the manual
that corresponds to your MySQL server version for the right syntax to
use near 'INSERT INTO student_attendance (attendance_date,
attendance_class_id, attendance' at line 1
include("../includes/db.php");
if(!empty($_POST)) {
$student_attendance_id = $_POST['student_attendance_id'];
$attendance_date = $_POST['attendance_date'];
$attendance_class_id = $_POST['attendance_class_id'];
$attendance_section_id = $_POST['attendance_section_id'];
$attendance_student_id = $_POST['attendance_student_id'];
if(isset($_POST['attendance_present_absent'])){
$attendance_present_absent = $_POST['attendance_present_absent'];
} else {
$attendance_present_absent = '';
}
$query = '';
for($count = 0; $count<count($attendance_student_id); $count++)
{
$attendance_date_now = mysqli_real_escape_string($connection, $attendance_date);
$student_attendance_id_now = mysqli_real_escape_string($connection, $student_attendance_id[$count]);
$attendance_class_id_now = mysqli_real_escape_string($connection, $attendance_class_id[$count]);
$attendance_section_id_now = mysqli_real_escape_string($connection, $attendance_section_id[$count]);
$attendance_student_id_now = mysqli_real_escape_string($connection, $attendance_student_id[$count]);
$attendance_present_absent_now = mysqli_real_escape_string($connection, $attendance_present_absent[$count]);
$query .= "INSERT INTO student_attendance (attendance_date, attendance_class_id, attendance_section_id, attendance_student_id, attendance_present_absent ) ";
$query .= "VALUES ('{$attendance_date_now}', '{$attendance_class_id_now}', '{$attendance_section_id_now}', '{$attendance_student_id_now}', '{$attendance_present_absent_now}' ) ";
echo $attendance_date_now;
echo $attendance_class_id_now . $attendance_section_id_now . "<br>";
}
$result = mysqli_multi_query($connection, $query) or die("Error :" . mysqli_error($connection));
Error 2:You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near ''attendance_date', 'attendance_class_id',
'attendance_section_id', 'attendance_s' at line 1
include("../includes/db.php");
if(!empty($_POST)) {
$student_attendance_id = $_POST['student_attendance_id'];
$attendance_date = $_POST['attendance_date'];
$attendance_class_id = $_POST['attendance_class_id'];
$attendance_section_id = $_POST['attendance_section_id'];
$attendance_student_id = $_POST['attendance_student_id'];
if(isset($_POST['attendance_present_absent'])){
$attendance_present_absent = $_POST['attendance_present_absent'];
} else {
$attendance_present_absent = '';
}
for($count = 0; $count<count($attendance_student_id); $count++)
{
$attendance_date_now = mysqli_real_escape_string($connection, $attendance_date);
$student_attendance_id_now = mysqli_real_escape_string($connection, $student_attendance_id[$count]);
$attendance_class_id_now = mysqli_real_escape_string($connection, $attendance_class_id[$count]);
$attendance_section_id_now = mysqli_real_escape_string($connection, $attendance_section_id[$count]);
$attendance_student_id_now = mysqli_real_escape_string($connection, $attendance_student_id[$count]);
$attendance_present_absent_now = mysqli_real_escape_string($connection, $attendance_present_absent[$count]);
$query .= "INSERT INTO student_attendance ('attendance_date', 'attendance_class_id', 'attendance_section_id', 'attendance_student_id', 'attendance_present_absent' ) ";
$query .= "VALUES ('{$attendance_date_now}', '{$attendance_class_id_now}', '{$attendance_section_id_now}', '{$attendance_student_id_now}', '{$attendance_present_absent_now}' ) ";
echo $attendance_date_now;
echo $attendance_class_id_now . $attendance_section_id_now . "<br>";
}
$result = mysqli_multi_query($connection, $query) or die("Error :" . mysqli_error($connection));
There are two mistakes. First is, in your for cycle you have to add ; after each INSERT string. Second, if you wanna use multiple insert, you should write INSERT part string before for cycle and then just add rows with values, there is , separator used.
include("../includes/db.php");
if(!empty($_POST)) {
$student_attendance_id = $_POST['student_attendance_id'];
$attendance_date = $_POST['attendance_date'];
$attendance_class_id = $_POST['attendance_class_id'];
$attendance_section_id = $_POST['attendance_section_id'];
$attendance_student_id = $_POST['attendance_student_id'];
if(isset($_POST['attendance_present_absent'])){
$attendance_present_absent = $_POST['attendance_present_absent'];
} else {
$attendance_present_absent = '';
}
$query = '';
for($count = 0; $count<count($attendance_student_id); $count++)
{
$attendance_date_now = mysqli_real_escape_string($connection, $attendance_date);
$student_attendance_id_now = mysqli_real_escape_string($connection, $student_attendance_id[$count]);
$attendance_class_id_now = mysqli_real_escape_string($connection, $attendance_class_id[$count]);
$attendance_section_id_now = mysqli_real_escape_string($connection, $attendance_section_id[$count]);
$attendance_student_id_now = mysqli_real_escape_string($connection, $attendance_student_id[$count]);
$attendance_present_absent_now = mysqli_real_escape_string($connection, $attendance_present_absent[$count]);
$query .= "INSERT INTO student_attendance (attendance_date, attendance_class_id, attendance_section_id, attendance_student_id, attendance_present_absent ) ";
$query .= "VALUES ('{$attendance_date_now}', '{$attendance_class_id_now}', '{$attendance_section_id_now}', '{$attendance_student_id_now}', '{$attendance_present_absent_now}' ); ";
echo $attendance_date_now;
echo $attendance_class_id_now . $attendance_section_id_now . "<br>";
}
$result = mysqli_multi_query($connection, $query) or die("Error :" . mysqli_error($connection));
OR
include("../includes/db.php");
if(!empty($_POST)) {
$student_attendance_id = $_POST['student_attendance_id'];
$attendance_date = $_POST['attendance_date'];
$attendance_class_id = $_POST['attendance_class_id'];
$attendance_section_id = $_POST['attendance_section_id'];
$attendance_student_id = $_POST['attendance_student_id'];
if(isset($_POST['attendance_present_absent'])){
$attendance_present_absent = $_POST['attendance_present_absent'];
} else {
$attendance_present_absent = '';
}
$query = 'INSERT INTO student_attendance (attendance_date, attendance_class_id, attendance_section_id, attendance_student_id, attendance_present_absent ) VALUES ';
for($count = 0; $count<count($attendance_student_id); $count++)
{
$attendance_date_now = mysqli_real_escape_string($connection, $attendance_date);
$student_attendance_id_now = mysqli_real_escape_string($connection, $student_attendance_id[$count]);
$attendance_class_id_now = mysqli_real_escape_string($connection, $attendance_class_id[$count]);
$attendance_section_id_now = mysqli_real_escape_string($connection, $attendance_section_id[$count]);
$attendance_student_id_now = mysqli_real_escape_string($connection, $attendance_student_id[$count]);
$attendance_present_absent_now = mysqli_real_escape_string($connection, $attendance_present_absent[$count]);
$query .= ($count>0?",":"") . "('{$attendance_date_now}', '{$attendance_class_id_now}', '{$attendance_section_id_now}', '{$attendance_student_id_now}', '{$attendance_present_absent_now}' )";
echo $attendance_date_now;
echo $attendance_class_id_now . $attendance_section_id_now . "<br>";
}
$query .= ";"
$result = mysqli_multi_query($connection, $query) or die("Error :" . mysqli_error($connection));

Update form with two file fields

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']))
?>
The error I get is:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'file = '', file_type = '', file_size = '' WHERE events.id = 1 LIMIT 1' at line 1
update
$query .= "`image_size` = '{$image_new_size}' ";
to
$query .= "`image_size` = '{$image_new_size}' ,";
so your final query
$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";

How to read JSON array in PHP and store it in MySQL

I'm newbie with PHP and JSON. I have a script that collects data from an JSON API and stores it in to MySQL data-base.
Script is working fine but I have a problem collecting specific array data.
This is the script :
<?php
$url="";
$db_name=" ";
$db_server=" ";
$db_user=" ";
$db_password="";
$newline=PHP_EOL;
$mysqli = new mysqli($db_server,$db_user, $db_password, $db_name);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}else{
echo "You are connected to the database ($db_name)" . $newline;
}
echo "Initial character set: ". $mysqli->character_set_name(). $newline;
if (!$mysqli->set_charset("utf8")) {
echo "Error loading character set utf8: ", $mysqli->error. $newline;
exit();
} else {
echo "Current character set: ", $mysqli->character_set_name(). $newline;
}
$json = file_get_contents($url . '1}');
$obj = json_decode(utf8_encode($json));
$totalPages=$obj->totalPages;
//read page
for($i = 1; $i < $totalPages ; $i++) {
echo "Read URL " . $url . $i . '}'. $newline;
$json = file_get_contents($url . $i . '}');
$obj = json_decode($json);
foreach($obj->items as $item){
$id = $item->id;
$Name=$item->name;
$FirstName = $item->firstName;
$LastName = $item->lastName;
$attributes = $item->attributes;
foreach($attributes as $attribute){
if ($attribute->name=="fut.attribute.DIV"){
$DIV = $attribute->value;
}
if ($attribute->name=="fut.attribute.POS"){
$POS = $attribute->value;
}
}
$r = $mysqli->query("SELECT id FROM DATABAS WHERE id=". $id);
if ($r->num_rows <= 0){ //INSERT
$query = "INSERT INTO DATABASE ( ";
$query.= "`id` , ";
$query.= "`Name` , ";
$query.= "`FirstName` , ";
$query.= "`LastName` , ";
$query.= "`DIV` ,";
$query.= "`POS` ) VALUES (";
$query.= $id . " , ";
$query.= "'" . $Name . "' , ";
$query.= "'" . $FirstName . "' , ";
$query.= "'" . $LastName . "' , ";
$query.= "'" . $DIV. "' , ";
$query.= "'" . $POS. "' ";
$query.= ");";
$mysqli->query($query);
echo "Last Name inserted was: " . $Name . $newline;
}else{ //UPDATE
$query = "UPDATE database ";
$query.= "SET `Name` ='".$Name."' , ";
$query.= "`FirstName` ='".$FirstName."' , ";
$query.= "`LastName` ='".$LastName."' , ";
$query.= "`DIV`='".$DIV."' , ";
$query.= "`POS`='".$POS."' ";
$query.= "WHERE id=".$id;
$mysqli->query($query);
echo "Last ID update was: " . $_id . $newline;
}
}
}
$mysqli->close();
function replace_unicode_escape_sequence($match) {
return mb_convert_encoding(pack('H*', $match[1]), 'UTF-8', 'UCS-2BE');
}
function unicode_decode($str) {
return preg_replace_callback('/\\\\u([0-9af]{4})/i', 'replace_unicode_escape_sequence', $str);
}
The Json data which I like to add is Traits "traits" and Specialties specialities. Data is stored with [] and I simply have now idea how to read it.
Attributes are stored likewise but have fixed names to point to.
This is partial Json data:
,"position":"RW","playStyle":"Basic","playStyleId":null,"height":170,"weight":72,"birthdate":"1987-06-24","age":29,"acceleration":99,"aggression":58,"agility":95,"balance":98,"ballcontrol":99,"foot":"Left","skillMoves":4,"crossing":90,"curve":99,"dribbling":99,"finishing":99,"freekickaccuracy":99,"gkdiving":6,"gkhandling":11,"gkkicking":15,"gkpositioning":14,"gkreflexes":8,"headingaccuracy":99,"interceptions":36,"jumping":82,"longpassing":89,"longshots":97,"marking":21,"penalties":82,"positioning":99,"potential":95,"reactions":95,"shortpassing":99,"shotpower":89,"slidingtackle":35,"sprintspeed":96,"standingtackle":38,"stamina":91,"strength":71,"vision":99,"volleys":94,"weakFoot":4,"traits":["Shooting - Finesse Shot","Dribbler - Speed Dribbler","One Club Player","Ultimate Professional"],"specialities":["Speedster","Dribbler","Distance Shooter","Crosser","FK Specialist","Acrobat","Clinical Finisher","Complete Forward","Poacher"],"atkWorkRate":"Medium","defWorkRate":"Low","playerType":"TEAM OF THE YEAR","attributes":[{"name":"fut.attribute.PAC","value":99,"chemistryBonus":[0]},{"name":"fut.attribute.SHO","value":98,"chemistryBonus":[0]},{"name":"fut.attribute.PAS","value":97,"chemistryBonus":[0]},{"name":"fut.attribute.DRI","value":99,"chemistryBonus":[0]},{"name":"fut.attribute.DEF","value":40,"chemistryBonus":[0]},{"name":"fut.attribute.PHY","value":75,"chemistryBonus":[0]}],"name":"Messi","quality":"gold","color":"toty","isGK":false,"positionFull":"Right
I really hoop some can help me. I try to find the solution myself but the solutions I have seen don’t correspond with the used code and my lack of knowledge on the subject is limiting me to implement it myself.
Or if you are using MySQL 5.7 just have a column in the table of data type JSON and just write the JSON object or array into it.
$arr = json_decode($json_obj,true);//decode object
foreach($arr as $ar){
$id = $ar["id"];
$name = $ar["name"];
$system_id = $ar["system_id"];
$max_landing_pad_size = $ar["max_landing_pad_size"];
$distance_to_star = $ar["distance_to_star"];
$faction = $ar["faction"];
$government = $ar["government"];
$allegiance = $ar["allegiance"];
$state = $ar["state"];
$type = $ar["type"];
$has_blackmarket = $ar["has_blackmarket"];
$has_commodities = $ar["has_commodities"];
$has_refuel = $ar["has_refuel"];
$has_repair = $ar["has_repair"];
$has_rearm = $ar["has_rearm"];
$has_outfitting = $ar["has_outfitting"];
$has_shipyard = $ar["has_shipyard"];
//insert values into mysql database
$sql="INSERT INTO stations (station_id, name, system_id, max_landing_pad_size, distance_to_star, faction, government, allegiance, state, type, has_blackmarket, has_commodities, has_refuel, has_repair, has_rearm, has_outfitting, has_shipyard)
VALUES ('$id', '$name', '$system_id', '$max_landing_pad_size', '$distance_to_star', '$faction', '$government', '$allegiance', '$state', '$type', '$has_blackmarket', '$has_commodities', '$has_refuel', '$has_repair', '$has_rearm', '$has_outfitting', '$has_shipyard')";
if(!mysql_query($sql,$con)) //$con is mysql connection object
{
die('Error : ' . mysql_error());
}
}

Categories