Use the result of an array as value of an Insert - PHP

Asked

Viewed 441 times

0

Good night, I’m having a doubt.

I am uploading a file and extracting its contents and inserting in my database, but I have a question how to use the array like the value

My file consists of a sequence of numbers separated by 15 block divided by one | and a line break between every 15 blocks

Ex. of Read File 02|01|020320171212|524419188|206|000011900173|03|700000|700000|644490|033438|2622221|C|M|C| |02|01|020320171427|524418372|206|000011915070|01|31900|31900|31102|250802|2623485|C|M|D|

Ex. of my code upload.php

<?php
include 'conect.php';
///RECEBE PELO METODO POST
if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0)
{
$tmpName  = $_FILES['userfile']['tmp_name'];
///ABRE O ARQUIVO
$fp      = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
///SEPARA OS BLOCOS
$array=explode("|",$content);

for($i = 0; $i < count($array); $i++) {

$query = mysql_query("INSERT INTO dados (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) VALUES ( '".$array[$i]."' ");
/// Está dando o erro de Query was empty

mysql_query($query) or die(mysql_error());

}


if(mysql_affected_rows() != 0){
echo "<script type='text/javascript'>window.alert('$fileName Enviado!');</script>";
echo '<meta HTTP-EQUIV="Refresh" CONTENT="1; URL=lista.php">';
exit;
}

}
?>

I want to enter in the database the information contained in this file so I created a table with columns in names of a,b,c...

If any of you can help me, I’d be grateful!

Att. Danilo Braga

2 answers

0


/!\ This publication TAKES NO ACCOUNT OF ANY SECURITY ASPECT!

That VALUES ( '".$array[$i]."' ") does not exist, at least not in this context, beyond the error that exists in its query who doesn’t have the ) at the end.


You can do it this way:

$valoresParaQuery = trim( trim( str_replace('|', "','", $linha) ) , "','");

$query = mysql_query("INSERT INTO dados (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) VALUES ( '" . $string . "') ");

The str_replace will replace all the | for , and the trim will remove any ',' before or after, that way:

INSERT INTO dados (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) VALUES ('02','01','020320171212','524419188','206','000011900173','03','700000','700000','644490','033438','2622221','C','M','C')

This still has error due to there being only 15 values against 16 columns, to fix it REMOVE the column that is AUTO_INCREMENT, thus removing the a.


But you say you have "a line break between every 15 blocks", if you want to insert all the lines do a loop per line, this is not being done in the current code.

Use for example:

include 'conect.php';

if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0){

    $tmpName  = $_FILES['userfile']['tmp_name'];

    $arquivo = file($tmpName);
    // Veja se o arquivo está exatamente no local, o `tmp_name` não informa o caminho do arquivo, normalmente na pasta /tmp/!

    foreach($arquivo as $linha){

        $valoresParaQuery = trim( trim( str_replace('|', "','", $linha) ) , "','");

        $query = mysql_query("INSERT INTO dados (b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) VALUES ('" . $valoresParaQuery . "') ");

    }

}

This way each line will be made the process described above, changing the | for , and then running the query.

Nor will I comment on security issues and vulnerabilities because there are many

  • Good morning @Inkeliz thanks for the help, but the bug still persists. Corrected the issue of ) at the end of mysql_querry and the fact that there are 16 columns for 15 elements is that it had not customized the names of the columns, where a would be the column with name ID and she will be AUTO_INCREMENT I’ll use the NULL as the first element of VALUE . At first I do not want to save the file in any directory, but do a temporary reading, so I did not indicate the file path. I am using this last code sent, plus the error of Query was empty still persists.

  • I fixed an error, but possibly your problem is totally different. Check if one var_dump(file($tmpName)) returns the file. I have tested exactly the above code using Mysqli using PHP 7.1, I am making it available at https://www.dropbox.com/s/v5cc2lz1uwwzag5/187952.zip?dl=0. If it is "AUTO_INCREMENT" do not need to mention it.

0

$content= str_replace("|".Chr(10)."|", Chr(10), $content);
$content= str_replace(Chr(10)."|", Chr(10), $content);

    $array= explode(Chr(10),$content);

    $result = count($array);                

    for ($k = 0; $k < $result; $k++) {
        $bloco = $array[$k];
        $aDest = explode("|", $bloco);
        $query = mysql_query("INSERT INTO spedido (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o) VALUES ('".$aDest[0]."','".$aDest[1]."','".$aDest[2]."','".$aDest[3]."','".$aDest[4]."','".$aDest[5]."','".$aDest[6]."','".$aDest[7]."','".$aDest[8]."','".$aDest[9]."','".$aDest[10]."','".$aDest[11]."','".$aDest[12]."','".$aDest[13]."','".$aDest[14]."') ");

Worked round on my bench with

$content="01|01|020320171212|524419188|206|000011900173|03|700000|700000|644490|033438|2622221|C|M|C| |02|01|020320171427|524418372|206|000011915070|01|31900|31900|31102|250802|2623485|C|M|D |03|01|020320171427|524418444|206|000011915070|01|31900|31900|31102|250802|2623485|C|M|D";

Browser other questions tagged

You are not signed in. Login or sign up in order to post.