Insert data into the database with php

Asked

Viewed 218 times

0

I’m trying to insert some data into the database via php, but it can’t add this data, would anyone know what it might be? I give a var_dump in the array to see if it is pulling the data correctly and it is. I want to pull the data from one table and send it to another. Just this, in case I can’t do it would have as I save this data I’m pulling into a file . sql? How would I do it with php?

Result var_dump

    array(27) {
  [0]=>
  string(1) "5"
  [1]=>
  string(1) "5"
  [2]=>
  string(5) "Elvis"
  [3]=>
  string(9) "Domingues"
  [4]=>
  string(1) "1"
  [5]=>
  string(1) "1"
  [6]=>
  NULL
  [7]=>
  NULL
  [8]=>
  string(14) "--------------"
  [9]=>
  NULL
  [10]=>
  NULL
  [11]=>
  NULL
  [12]=>
  string(13) "teste apelido"
  [13]=>
  NULL
  [14]=>
  string(1) "1"
  [15]=>
  NULL
  [16]=>
  NULL
  [17]=>
  NULL
  [18]=>
  string(33) "elvis.domingues@----------"
  [19]=>
  NULL
  [20]=>
  NULL
  [21]=>
  string(19) "1979-04-06 00:00:00"
  [22]=>
  string(11) "------------"
  [23]=>
  string(1) "1"
  [24]=>
  NULL
  [25]=>
  NULL
  [26]=>
  NULL
}
Erro ao inserir cliente 

Code

   $users = Mage::getModel('customer/customer')->getCollection();

    $i = 1;
    foreach ($users as $key => $user) {
    $id = $user->getId();

    $usuario_loaded = Mage::getModel('customer/customer')->load($id);

                $tudo = array(
                $id = $usuario_loaded->getId(),
                $clientes_id = $usuario_loaded->getId(),  
                $nome = $usuario_loaded->getFirstname(),
                $sobrenome = $usuario_loaded->getLastname(),
                $loja = $usuario_loaded->getWebsiteId(),
                $grupo = $usuario_loaded->getGroupId(),
                $prefixo = $usuario_loaded->getPrefix(),
                $assinatura = $usuario_loaded->getMiddlename(),
                $cpf = $usuario_loaded->getCpf(),
                $cnpj = $usuario_loaded->getCnpj(),
                $razao = $usuario_loaded->getCompanyName(),
                $fantasia = $usuario_loaded->getTradingName(),
                $apelido = $usuario_loaded->getNickname(),
                $insestadual = $usuario_loaded->getIe(),
                $tipocadastro = $usuario_loaded->getType(),
                $profissao = $usuario_loaded->getOccupation(),
                $fundação = $usuario_loaded->getFoundationDay(),
                $sufixo = $usuario_loaded->getSuffix(),
                $email = $usuario_loaded->getEmail(),
                $emailsec = $usuario_loaded->getEmailSeconday(),
                $emailfiscal = $usuario_loaded->getEmailBilling(),
                $nascimento = $usuario_loaded->getDob(),
                $cpfcnpj = $usuario_loaded->getTaxvat(),
                $sexo = $usuario_loaded->getGender(),
                $departamento = $usuario_loaded->getDepartment(),
                $ondeconheceu = $usuario_loaded->getHowFindUs(),
                $adyen = $usuario_loaded->getAdyenCustomerRef());  

 var_dump($tudo);

     $strcon = mysqli_connect('localhost','root','','teste2') or die('Erro ao conectar ao banco de dados');
                $sql = mysqli_query($strcon,
                "INSERT INTO clientes(
                         id
                         clientes_id,
                         nome,
                         sobrenome,
                         loja,
                         grupo,
                         prefixo,
                         assinatura,
                         cpf,
                         cnpj,
                         razao,
                         fantasia,
                         apelido,
                         insestadual,
                         tipocadastro,
                         profissao,
                         fundação,
                         sufixo,
                         email,
                         emailsec,
                         emailfiscal,
                         nascimento,
                         cpfcnpj,
                         sexo,
                         departamento,
                         ondeconheceu,
                         adyen) 
                         VALUES (
                         '$id',
                         '$clientes_id',
                         '$nome',
                         '$sobrenome',
                         '$loja',
                         '$grupo',
                         '$prefixo',
                         '$assinatura',
                         '$cpf',
                         '$cnpj',
                         '$razao',
                         '$fantasia',
                         '$apelido',
                         '$insestadual',
                         '$tipocadastro',
                         '$profissao',
                         '$fundação',
                         '$sufixo',
                         '$email',
                         '$emailsec',
                         '$emailfiscal',
                         '$nascimento',
                         '$cpfcnpj',
                         '$sexo',
                         '$departamento',
                         '$ondeconheceu',
                         '$adyen')");
                        mysqli_query($strcon,
                        $sql) or die("Erro ao inserir cliente \n"); 
  • your array is with sequential keys, in Insert you are using variables that by what I see are not instantiated, it would be interesting to convert your array in the correct variables or adjust the keys of it to be able to use directly

  • I forgot to put the variables here in the question, but I have them in the code, careless man.

  • You intend to copy the same data from one table to another?

  • Yeah, that’s pretty much it. only that I would like to remove this data and put again in another table, I would not like to do this by mysql changing the tables..

  • Bank table or page table in view? Like take from a table of the bank and put soon in another or see want to remove the data to show on the page and then send back to the bank?

  • Database table, I pull the data from this table (Customer/Customer) and then I would like to insert these same data into another table

  • @adventistaam It can be any of the ways, I would like to put this data in another table, but if it is not possible to remove this data in a document to then I insert them, I think putting in another direct table is less work, because there I will have this same data.

  • You can do it like this: INSERT INTO 'tabela2' 
 ( 'codigo','cliente_id','nome', 'sobrenome', 'loja')
 SELECT 'id', 'cliente_id', 'nome', 'sobrenome', 'loja' FROM 'customer' WHERE
 'id' = 1

  • Didn’t work...

  • What a mistake you made?

  • Works for me.

  • The other way would be for you to save the object directly to the Insert. For example: INSERT INTO sua_tabela ( 'codigo', 'cliente_id', etc ) VALUES ( $tudo[0], $tudo[1], etc )

  • I got it here now, it was a syntax error I was having, already managed to fix, based on your comments, thank you very much @adventistaam

  • 1

    That other suggestion was according to your var_dump, but I’m glad it worked

  • @adventistaam Yes, now I’m having another mistake, by the customer using ' in his last name, example D'souza gives an error on account of the >'< you’ve seen something like?

  • 1

    Vixe. I’ve been through this, you put the str_replace("'","'",$customer);

Show 11 more comments

2 answers

1


Solution

    $users = Mage::getModel('customer/customer')->getCollection();

    $i = 1;
    foreach ($users as $key => $user) {
    $id = $user->getId();

    $usuario_loaded = Mage::getModel('customer/customer')->load($id);

    $tudo = array('id'=>$usuario_loaded->getId(), 'clientes_id'=>$usuario_loaded->getId(), 'nome'=>$usuario_loaded->getFirstname(), 'sobrenome'=>$usuario_loaded->getLastname(), 'loja'=>$usuario_loaded->getWebsiteId(), 'grupo'=>$usuario_loaded->getGroupId(), 'prefixo'=>$usuario_loaded->getPrefix(), 'assinatura'=>$usuario_loaded->getMiddlename(), 'cpf'=>$usuario_loaded->getCpf(), 'cnpj'=>$usuario_loaded->getCnpj(), 'razao'=>$usuario_loaded->getCompanyName(), 'fantasia'=>$usuario_loaded->getTradingName(), 'apelido'=>$usuario_loaded->getNickname(), 'insestadual'=>$usuario_loaded->getIe(), 'tipocadastro'=>$usuario_loaded->getType(), 'profissao'=>$usuario_loaded->getOccupation(), 'fundação'=>$usuario_loaded->getFoundationDay(), 'sufixo'=>$usuario_loaded->getSuffix(), 'email'=>$usuario_loaded->getEmail(), 'emailsec'=>$usuario_loaded->getEmailSeconday(), 'emailfiscal'=>$usuario_loaded->getEmailBilling(), 'nascimento'=>$usuario_loaded->getDob(), 'cpfcnpj'=>$usuario_loaded->getTaxvat(), 'sexo'=>$usuario_loaded->getGender(), 'departamento'=>$usuario_loaded->getDepartment(), 'ondeconheceu'=>$usuario_loaded->getHowFindUs(), 'adyen'=>$usuario_loaded->getAdyenCustomerRef());


                var_dump($tudo);

                $connection = Mage::getSingleton('core/resource')->getConnection('core_write');
                $query = "INSERT INTO clientes (`id`, `clientes_id`, `nome`, `sobrenome`, `loja`, `grupo`, `prefixo`, `assinatura`, `cpf`, `cnpj`, `razao`, `fantasia`, `apelido`, `insestadual`, `tipocadastro`, `profissao`, `fundação`, `sufixo`, `email`, `emailsec`, `emailfiscal`, `nascimento`, `cpfcnpj`, `sexo`, `departamento`, `ondeconheceu`, `adyen`) VALUES ('".$tudo['id']."', '".$tudo['clientes_id']."', '".$tudo['nome']."', '".$tudo['sobrenome']."', '".$tudo['loja']."', '".$tudo['grupo']."', '".$tudo['prefixo']."', '".$tudo['assinatura']."', '".$tudo['cpf']."', '".$tudo['cnpj']."', '".$tudo['razao']."', '".$tudo['fantasia']."', '".$tudo['apelido']."', '".$tudo['insestadual']."', '".$tudo['tipocadastro']."', '".$tudo['profissao']."', '".$tudo['fundação']."', '".$tudo['sufixo']."', '".$tudo['email']."', '".$tudo['emailsec']."', '".$tudo['emailfiscal']."', '".$tudo['nascimento']."', '".$tudo['cpfcnpj']."', '".$tudo['sexo']."', '".$tudo['departamento']."', '".$tudo['ondeconheceu']."', '".$tudo['adyen']."')";
                $connection->query($query);

1

Second comment eu puxo os dados dessa tabela (customer/customer) e depois gostaria de inserir esses mesmos dados em outra tabela

It can be done that way:

$conn = new mysqli ("localhost", "USUARIO", "SENHA", "Nome_DB");

    $array = array();   

    $sql = ("SELECT * FROM Nome_Tabela");

    $result = $conn->query($sql);

    while($row = $result->fetch_assoc())
    {
        $array[] = $row;
    }               

    $i = 0;
    foreach ($array as $value) {

        $var1 = $array[$i]['NomeColuna1'];
        $var2 = $array[$i]['NomeColuna2'];
        $var3 = $array[$i]['NomeColuna3'];
        .............................
        .............................
        $conn->query("INSERT INTO Nome_Nova_Tabela VALUES ('','$var1','$var2,'$var3', ..........')");
        $i++;

    }

mysqli_close($conn);

You can simplify in foreach like this:

$i = 0;
foreach ($array as $value) {
    $conn->query("INSERT INTO Nome_Nova_Tabela VALUES ('', '".$array[$i]['NomeColuna1']."', '".$array[$i]['NomeColuna2']."', '".$array .......)");
    $i++;

}
  • It has already been solved, but thanks for your comment! For using the platform $users = Mage::getModel('customer/customer')->getCollection(); is his own method of pulling the data giving the gets getName();. It has a well differentiated table structure where each table stores information, but I pull this way I can get all the information I need. That’s why I didn’t give a direct select in the table.

  • @Gustavosouza no more I ended up learning something else from you :) In that case I will remove my answer. I know nothing of Magento

  • 1

    You who knows, for being a data insertion via PHP "pure" yours can help other people, I think information is never enough, your code is easy to understand and can be help someone.

  • @Gustavosouza ok convinced me

Browser other questions tagged

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