Record personal communication data

2

I'm trying to write to a person's BD communication data and I'm not able to resolve it, the data in that communication is Email , Telefone Empresa , Celular Empresa and Ramal , each of these are registered types in a table called cadTipoComunicacao and later I try to write that data to a table called cadComunicacao.

I have the information available:

    // TIPOS DE COMUNICAÇÃO
    $IdTipoRamal = 1;   
    $IdTipoTe = 3;
    $IdTipoCe = 4;
    $IdTipoEmail = 6;

    // INFORMAÇÃO
    $Ramal = 1820;  
    $TelEmpresa = '(44) 3733-8810';
    $CelEmpresa = '(44) 99898-8585';    
    $Email = '[email protected]';

And the following structure for agrupar information:

    $Registros = array (
      array($IdTipoRamal,$Ramal),     
      array($IdTipoTe, $TelEmpresa),
      array($IdTipoCe, $CelEmpresa),
      array($IdTipoEmail, $Email)
    );

What am I doing to display the information:

for ($row = 0; $row < 4; $row++) {   
  echo "<ul>";
  for ($col = 0; $col < 2; $col++) {
    echo "<li>".$Registros[$row][$col]."</li>";
  }
  echo "</ul>";
}

The output of this code is this:

TheInsertcodeoftheattemptImadeisthis:

//DADOSDACOMUNICAÇÃO$Registros=array(array($IdTipoRamal,$Ramal),array($IdTipoTe,$TelEmpresa),array($IdTipoCe,$CelEmpresa),array($IdTipoEmail,$Email));//INSERIRfor($row=0;$row<4;$row++){//echo"<ul>";
  for ($col = 0; $col < 2; $col++) {
    // echo "<li>".$Registros[$row][$col]."</li>";

    $crud = $pdo->prepare("INSERT INTO cadComunicacao ( IdPessoa, IdTipo, Informacao ) VALUES (?, ?, ?)");
    $crud->bindParam(1, $IdPessoa , PDO::PARAM_INT);
    $crud->bindParam(2, $IdTipo , PDO::PARAM_INT);
    $crud->bindParam(3, $Informacao , PDO::PARAM_STR);
    $retorno = $crud->execute();           

  }
  // echo "</ul>";
} 

What I am not able to do is to loop through and write TypeType and Information, in the image the IdType is the first value and the Information is the second.

I can not write everything to the Informacao field, I need to loop through and write the IdPessoa , IdTipo and the 'Information', which in the case above can be multiple lines for Type and Information Id.

The table cadComunicacao, where I am trying to write the information has this structure:

    
asked by anonymous 19.06.2017 / 20:05

1 answer

3

I think it made a lot of confusion in the way you pull data to insert into the table, you can simplify using foreach , see how:

$IdPessoa = 1;
$IdTipoRamal = 1;   
$IdTipoTe = 3;
$IdTipoCe = 4;
$IdTipoEmail = 6;
$Ramal = 1820;  
$TelEmpresa = '(44) 3733-8810';
$CelEmpresa = '(44) 99898-8585';    
$Email = '[email protected]';
$Registros = array (
    array($IdTipoRamal,$Ramal),     
    array($IdTipoTe, $TelEmpresa),
    array($IdTipoCe, $CelEmpresa),
    array($IdTipoEmail, $Email)
);
foreach($Registros as &$value){
    $crud = $pdo->prepare("INSERT INTO cadComunicacao ( IdPessoa, IdTipo, Informacao ) VALUES (?, ?, ?)");
    $crud->bindParam(1, $IdPessoa , PDO::PARAM_INT);
    $crud->bindParam(2, $value[0] , PDO::PARAM_INT);
    $crud->bindParam(3, $value[1] , PDO::PARAM_STR);
    $retorno = $crud->execute(); 
}

If you want to try to simplify, just do one execute instead of several, you can try to do this (although I prefer the first form):

$sql = "INSERT INTO cadComunicacao ( IdPessoa, IdTipo, Informacao ) VALUES ";
foreach($Registros as &$value){
    $sql .= "(?, ?, ?),";
}
$sql = substr($sql, 0, -1);
$crud = $pdo->prepare($sql);
$i = 1;
foreach($Registros as &$value){
    $crud->bindParam($i++, $IdPessoa , PDO::PARAM_INT);
    $crud->bindParam($i++, $value[0] , PDO::PARAM_INT);
    $crud->bindParam($i++, $value[1] , PDO::PARAM_STR);
}
$retorno = $crud->execute(); 

TL; DR:

I recommend that you do this procedure within try... catch , if there is an error, it is easier to treat, something like this:

try {
    $crud = $pdo->prepare($sql);
    $i = 1;
    foreach($Registros as &$value){
        $crud->bindParam($i++, $IdPessoa , PDO::PARAM_INT);
        $crud->bindParam($i++, $value[0] , PDO::PARAM_INT);
        $crud->bindParam($i++, $value[1] , PDO::PARAM_STR);
    }
    $retorno = $crud->execute();                    
} catch (PDOException $e) {
    die($e);
}

One last but not least tip

Within try catch I showed a way to display the errors on the screen, but this should not be done in a production environment .... be careful because it exposes your structure a bit, and it's also nothing fancy show such an error to clients

What can be done is to create a function that logs these errors, either in a .txt file, or in the database for example.

How I usually do:

function create_log( $filename, $string ) {
    date_default_timezone_set( 'America/Sao_Paulo' );
    file_put_contents( $filename, date( 'r' )." ".$string.PHP_EOL, FILE_APPEND );
}

And within try catch :

try {
  // Código      
} catch (PDOException $e) {
  http_response_code(500);
  // Removo todas informações que não devem ser salvas no log
  unset($_POST["senha"]);
  create_log( "logs/db_errors.log", "Informação adicional.PHP_EOL.json_encode($_POST).PHP_EOL."Exception: ".$e );
  // Com uma transaction ativa, comando desfaz tudo que foi feito no banco de dados
  // $db->rollBack();
  // Com uma transaction ativa, comando "salva" tudo que foi feito no banco de dados antes do erro que gerou a exception 
  // $db->commit();
  // Utilize a que melhor se adeque no seu caso
  die(); // Retorno vazio
}
    
27.06.2017 / 22:03