Related
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
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";
Just wondering if anyone can point me in the direction of some tips / a script that will help me create an mysql from an original dbf File, using PHP.
thanks before.
Try the code below...
<?php
$tbl = "cc";
$db_uname = 'root';
$db_passwd = '';
$db = 'aa';
$conn = mysql_pconnect('localhost',$db_uname, $db_passwd);
// Path to dbase file
$db_path = "dbffile/bbsres12.dbf";
// Open dbase file
$dbh = dbase_open($db_path, 0) or die("Error! Could not open dbase database file '$db_path'.");
// Get column information
$column_info = dbase_get_header_info($dbh);
// Display information
// print_r($column_info);
$line = array();
foreach($column_info as $col) {
switch($col['type']) {
case 'character':
$line[]= "`$col[name]` VARCHAR( $col[length] )";
break;
case 'number':
$line[]= "`$col[name]` FLOAT";
break;
case 'boolean':
$line[]= "`$col[name]` BOOL";
break;
case 'date':
$line[]= "`$col[name]` DATE";
break;
case 'memo':
$line[]= "`$col[name]` TEXT";
break;
}
}
$str = implode(",",$line);
$sql = "CREATE TABLE `$tbl` ( $str );";
mysql_select_db($db, $conn);
mysql_query($sql, $conn);
set_time_limit(0); // I added unlimited time limit here, because the records I imported were in the hundreds of thousands.
// This is part 2 of the code
import_dbf($db, $tbl, $db_path);
function import_dbf($db, $table, $dbf_file) {
global $conn;
if (!$dbf = dbase_open ($dbf_file, 0)) {
die("Could not open $dbf_file for import.");
}
$num_rec = dbase_numrecords($dbf);
$num_fields = dbase_numfields($dbf);
$fields = array();
for ($i=1; $i<=$num_rec; $i++) {
$row = #dbase_get_record_with_names($dbf,$i);
$q = "insert into $db.$table values (";
foreach ($row as $key => $val) {
if ($key == 'deleted') {
continue;
}
$q .= "'" . addslashes(trim($val)) . "',"; // Code modified to trim out whitespaces
}
if (isset($extra_col_val)) {
$q .= "'$extra_col_val',";
}
$q = substr($q, 0, -1);
$q .= ')';
//if the query failed - go ahead and print a bunch of debug info
if (!$result = mysql_query($q, $conn)) {
print (mysql_error() . " SQL: $q\n");
print (substr_count($q, ',') + 1) . " Fields total.";
$problem_q = explode(',', $q);
$q1 = "desc $db.$table";
$result1 = mysql_query($q1, $conn);
$columns = array();
$i = 1;
while ($row1 = mysql_fetch_assoc($result1)) {
$columns[$i] = $row1['Field'];
$i++;
}
$i = 1;
foreach ($problem_q as $pq) {
print "$i column: {$columns[$i]} data: $pq\n";
$i++;
}
die();
}
}
}
?>
You can try composer package hisamu/php-xbase (https://github.com/hisamu/php-xbase) to read dbf file and insert into your database. Had the same problem and this was most suitable solution.
UPDATED:
in the event that your did not compile PHP with dbase library you could get the following error:
Call to undefined function dbase_open()
in which case (centos)
yum install php-dbase
Here is the updated code for $mysqli
<?php
$mysqli = new mysqli("localhost", "DBusername", "DBpassword", "tableName");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$tbl = "yourTableName";
$db = 'YourDBName';
// Path to dbase file
$db_path = "/path/dbaseFileName.dbf";
// Open dbase file
$dbh = dbase_open($db_path, 0)
or die("Error! Could not open dbase database file '$db_path'.");
// Get column information
$column_info = dbase_get_header_info($dbh);
$line = array();
foreach($column_info as $col) {
switch($col['type']){
case 'character':
$line[]= "`$col[name]` VARCHAR( $col[length] )";
break;
case 'number':
$line[]= "`$col[name]` FLOAT";
break;
case 'boolean':
$line[]= "`$col[name]` BOOL";
break;
case 'date':
$line[]= "`$col[name]` DATE";
break;
case 'memo':
$line[]= "`$col[name]` TEXT";
break;
}
}
$str = implode(",",$line);
$sql = "CREATE TABLE `$tbl` ( $str );";
//mysql_select_db($db,$conn);
//mysql_query($sql,$conn);
$mysqli->query($sql);
set_time_limit(0); // I added unlimited time limit here, because the records I imported were in the hundreds of thousands.
// This is part 2 of the code
import_dbf($db, $tbl, $db_path, $mysqli);
function import_dbf($db, $table, $dbf_file,$mysqli){
//global $conn;
global $mysqli;
if (!$dbf = dbase_open ($dbf_file, 0)){ die("Could not open $dbf_file for import."); }
$num_rec = dbase_numrecords($dbf);
$num_fields = dbase_numfields($dbf);
$fields = array();
for ($i=1; $i<=$num_rec; $i++){
$row = #dbase_get_record_with_names($dbf,$i);
$q = "insert into $db.$table values (";
foreach ($row as $key => $val){
if ($key == 'deleted'){ continue; }
$q .= "'" . addslashes(trim($val)) . "',"; // Code modified to trim out whitespaces
}
if (isset($extra_col_val)){ $q .= "'$extra_col_val',"; }
$q = substr($q, 0, -1);
$q .= ')';
//if the query failed - go ahead and print a bunch of debug info
// if (!$result = mysql_query($q, $conn)){
if (!$result = $mysqli->query($q)){
print (mysql_error() . " SQL: $q\n");
print (substr_count($q, ',') + 1) . " Fields total.";
$problem_q = explode(',', $q);
$q1 = "desc $db.$table";
//$result1 = mysql_query($q1, $conn);
$result1 = $mysqli->query($q1);
$columns = array();
$i = 1;
while ($row1 = $result1->fetch_assoc()){
$columns[$i] = $row1['Field'];
$i++;
}
$i = 1;
foreach ($problem_q as $pq){
print "$i column: {$columns[$i]} data: $pq\n";
$i++;
}
die();
}
}
}
$mysqli->close();
?>
<?php
$mysqli = new mysqli("localhost", "DBusername", "DBpassword", "tableName");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$tbl = "yourTableName";
$db = 'YourDBName';
// Path to dbase file
$db_path = "/path/dbaseFileName.dbf";
// Open dbase file
$dbh = dbase_open($db_path, 0)
or die("Error! Could not open dbase database file '$db_path'.");
// Get column information
$column_info = dbase_get_header_info($dbh);
$line = array();
foreach($column_info as $col) {
switch($col['type']){
case 'character':
$line[]= "`$col[name]` VARCHAR( $col[length] )";
break;
case 'number':
$line[]= "`$col[name]` FLOAT";
break;
case 'boolean':
$line[]= "`$col[name]` BOOL";
break;
case 'date':
$line[]= "`$col[name]` DATE";
break;
case 'memo':
$line[]= "`$col[name]` TEXT";
break;
}
}
$str = implode(",",$line);
$sql = "CREATE TABLE `$tbl` ( $str );";
//mysql_select_db($db,$conn);
//mysql_query($sql,$conn);
$mysqli->query($sql);
set_time_limit(0); // I added unlimited time limit here, because the records I imported were in the hundreds of thousands.
// This is part 2 of the code
import_dbf($db, $tbl, $db_path, $mysqli);
function import_dbf($db, $table, $dbf_file,$mysqli){
//global $conn;
global $mysqli;
if (!$dbf = dbase_open ($dbf_file, 0)){ die("Could not open $dbf_file for import."); }
$num_rec = dbase_numrecords($dbf);
$num_fields = dbase_numfields($dbf);
$fields = array();
for ($i=1; $i<=$num_rec; $i++){
$row = #dbase_get_record_with_names($dbf,$i);
$q = "insert into $db.$table values (";
foreach ($row as $key => $val){
if ($key == 'deleted'){ continue; }
$q .= "'" . addslashes(trim($val)) . "',"; // Code modified to trim out whitespaces
}
if (isset($extra_col_val)){ $q .= "'$extra_col_val',"; }
$q = substr($q, 0, -1);
$q .= ')';
//if the query failed - go ahead and print a bunch of debug info
// if (!$result = mysql_query($q, $conn)){
if (!$result = $mysqli->query($q)){
print (mysql_error() . " SQL: $q\n");
print (substr_count($q, ',') + 1) . " Fields total.";
$problem_q = explode(',', $q);
$q1 = "desc $db.$table";
//$result1 = mysql_query($q1, $conn);
$result1 = $mysqli->query($q1);
$columns = array();
$i = 1;
while ($row1 = $result1->fetch_assoc()){
$columns[$i] = $row1['Field'];
$i++;
}
$i = 1;
foreach ($problem_q as $pq){
print "$i column: {$columns[$i]} data: $pq\n";
$i++;
}
die();
}
}
}
$mysqli->close();
?>