I’m trying to insert excel datas in mysql with php, I have a code but it’s inserting only the first line off the archive and my archive has 3 lines.
Someone knows how to help me?
public function incluirLote() { if (!empty($_FILES['arquivo']['tmp_name'])) { $arquivo = new DOMDocument; $arquivo->load($_FILES['arquivo']['tmp_name']); $linhas = $arquivo->getElementsByTagName("Row"); $countlinha = 1; foreach ($linhas as $linha) { if ($countlinha > 1) { $nome = $linha->getElementsByTagName("Data")->item(0)->nodeValue; echo "Nome: $nome <br>"; $email = $linha->getElementsByTagName("Data")->item(1)->nodeValue; echo "E-mail: $email <br>"; $niveis_acesso_id = $linha->getElementsByTagName("Data")->item(2)->nodeValue; echo "Nivel de Acesso: $niveis_acesso_id <br>"; echo "<hr>"; $conn = $this->connect(); $sql = "insert into usu (nome, email, niveis_acesso_id) VALUES (:nome, :email, :niveis_acesso_id) "; $stmt = $conn->prepare($sql); $stmt->bindParam(':nome', $nome); $stmt->bindParam(':email', $email); $stmt->bindParam(':niveis_acesso_id', $niveis_acesso_id); $stmt->execute(); return $stmt; } $countlinha++; } } }
Advertisement
Answer
Your script has the following happening:
You set $countlinha = 1;
Which means the condition if ($countlinha > 1)
is false
on first iteration of foreach($linhas as $linha)
. I.e. the first ‘record’ inside $linhas
is not processed.
Then you increment $countlinha++;
it becomes 2
So on second iteration of foreach($linhas as $linha)
the code inside the if ($countlinha > 1)
is executed.
The second ‘record’ inside $linhas
is echoed and written to database.
However, return $stmt;
now terminates your script.
So all in all you only got one ‘record’ processed.
TLDR
If you want to get all ‘records’ inside $linhas
processed, you should drop the if ($countlinha > 1)
condition, and do NOT return
inside the loop as it will terminate your script prematurely.