I need to separate strings to import to mysql

Asked

Viewed 80 times

0

I need to separate each string to be able to import into the database, as I would?

link to the file I’m testing https://camisetasdecorrida.com.br/usuarios2.csv

            <?php 

            include_once("../conn/conexao.php");

            if ($_SERVER["REQUEST_METHOD"] === "POST") {

                $filename = $_FILES["file1"];

                if ($filename["error"]) {
                    throw new Exception("Error: ".$filename["error"]);
                }

                $dirUploads = "../uploads";

                if (move_uploaded_file($filename["tmp_name"], $dirUploads . DIRECTORY_SEPARATOR . $filename["name"])) {
                    echo "Upload Realizado com sucesso";
                }else {

                    throw new Exception("Não foi possivel fazer o upload.");


                }
            }

            $filename = $dirUploads . DIRECTORY_SEPARATOR . 
            $filename["name"];


            if(file_exists($filename)) {

                $file = fopen($filename, "r");

                $headers = explode(",", fgets($file));

                $data = array();

                while ($row = utf8_encode(fgets($file))) {

                    $rowData = explode(",", $row);
                    $linha = array();

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

                        $linha[$headers[$i]] = $rowData[$i];
                    }

                    array_push($data, $linha);

                    //$query1 = mysqli_query($conn, "INSERT 'clientes' SET nome='$row[1]', responsavel = '', endereco = '$row[4]', endereco_entrega = '', cpf = '$row[12]', telefone = '', cidade_estado = '', ie = '', cep = ''") or print mysql_error();

                }
                echo "<br>";
                /*if ($query1) {

                    echo "Tudo certo";
                }else {
                    echo "erro";
                }
                echo "<br>";*/




                fclose($file);


                //echo json_encode($data);
                //var_dump($data);
            }

             ?>
  • Explain your problem better, it’s too vague.

  • I need to make a client import system, however I need to separate each client by part using a while, like the name would have to separate from each client to make an INSERT in the database

1 answer

0


You are using the function explode and trying to separate the string by comma, however, the CSV is using semicolon (;) as a separator.

Another detail, you can use the function fgetcsv. Just set the third parameter as a semicolon.

$headers = fgetcsv($file , 0 , ';');
  • And how would I pull each string? $Row[0]

  • Just replace in the while of your code, in the same way as the example (removing the utf8_encode)

Browser other questions tagged

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