PDO isn't importing to MySql

Hey Guys, first sorry for my english!

I started learning PDO and I want to import a csv file to MySql and my code doesn’t work.
Where is my mistake?

My code:

<?php

$conn = new PDO("mysql:host=localhost;dbname=fabio", "root", "");
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

	$filename = ($_FILES['arquivocsv2']["tmp_name"]);
$abraArq = fopen($filename,"r");
$import = $conn->prepare("INSERT INTO relatorio (DocumentoSD,Descricao,CodCliente,Cliente,Regiao,DataDocumento,Material,Condicoes,Plano)VALUES (:DocumentoSD, :Descricao, :CodCliente, :Cliente, :Regiao, :DataDocumento, :Material, :Condicoes, :Plano)");

$import->bindParam(':DocumentoSD', $DocumentoSD,PDO::PARAM_STR);
$import->bindParam(':Descricao', $Descricao,PDO::PARAM_STR);
$import->bindParam(':CodCliente', $CodCliente,PDO::PARAM_STR);
$import->bindParam(':Cliente', $Cliente,PDO::PARAM_STR);
$import->bindParam(':Regiao', $Regiao,PDO::PARAM_STR);
$import->bindParam(':DataDocumento', $DataDocumento,PDO::PARAM_STR);
$import->bindParam(':Material', $Material,PDO::PARAM_STR);
$import->bindParam(':Condicoes', $Condicoes,PDO::PARAM_STR);
$import->bindParam(':Plano', $Plano,PDO::PARAM_STR);

while (($items = fgetcsv($abraArq, 2048, ';')) !== FALSE) {

$DocumentoSD = $items[0];
$Descricao = $items[4];
$CodCliente = $items[5];
$Cliente = $items[6];
$Regiao = $items[7];
$DataDocumento = $items[10];
$Material = $items[11];
$Condicoes = $items[17];
$Plano = $items[29];
			// Execute prepared query
$import->execute();}
?>

How is it not working?

  • Is it giving you an error? If so, what error?
  • If it’s not importing any values into your database, are you sure the loop is working? Are you actually reading from the csv file.

It isn’t accepting caracter especial.

But I’m doing it using prepare statment, and doesn’t it work for that?

You need to specify the character set in your connection string.

array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")
2 Likes

sorry, but it didn’t work.
I paste it here:
$conn = new PDO(“mysql:host=localhost;dbname=fabio”, “root”, “”,array(PDO::MYSQL_ATTR_INIT_COMMAND => “SET NAMES utf8”));

Setting character set in PDO like that just won’t work. You also need to modify the database encoding as well.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.