How to insert in mysql using foreach? [closed]

0

Hello, I have a code where I get the data coming from a webservice and I save it in variables.

I would like to Inserir/Salvar this data in my database MySQL . However I get this data through a foreach(){...}

// Pegar os leads
    $leads = $client->leads->getLeads([]);

// Pegando os leads
    foreach($leads->contacts as $contacts)
    {
        // Salvando dados nas variáveis
            $nome    = $contacts->name;
            $id      = $contacts->id;
            $tags    = $contacts->tags;

        // Percorrendo os dados
            foreach($tags->tags as $objeto)
            {
                $tag  = $objeto->name;
            }   
    }

according to the code above. How could I insert this data in a way that would look like this in the table [example] table:

  

[ID] [NOME] [TAGS]

     

[01] [JOSÉ] [tag1,tag2,tag3..]

Well, if I create a query like this:

  

$query = mysqli_query($conexao,"INSERT INTO leads(nome,tags) VALUES ('$nome','$tag')";

Each foreach(){..} would have a different tag and would overwrite the tag value. >     

asked by anonymous 01.02.2017 / 13:59

3 answers

7

Instead of scrolling through the list of tags of each record, being a vector, you can make them a single object in the JSON format and store them only once for each record.

$leads = $client->leads->getLeads([]);

foreach($leads->contacts as $contacts)
{
    $nome    = $contacts->name;
    $id      = $contacts->id;
    $tags    = $contacts->tags;

    // Aqui você serializa o vetor de tags:
    $tags = json_encode($tags);

    // Agora execute a sua *query* de INSERT:
    $query = mysqli_query($conexao, "INSERT INTO leads(nome, tags) VALUES ('$nome', '$tags')");

}

In this way, tags will be saved in the database in the format similar to the [tag1, rag2, tag3...] , with the brackets. When it comes to retrieving the data from the database, just run $tags = json_decode($tags) that you will have the tags vector again.

    
01.02.2017 / 14:11
2

You can use Implode

You can use implode from php to merge the tags and write to a varchar field %.

$tags = implode(",", $contacts->tags);

If you need to do Insert or Update you can use a INSERT ... ON DUPLICATE KEY UPDATE command from MySQL. See an example in this SO issue

    
01.02.2017 / 14:22
1

If $contacts->tags; is an array use implode :

$leads = $client->leads->getLeads([]);

foreach($leads->contacts as $contacts)
{
    $nome    = $contacts->name;
    $id      = $contacts->id;
    $tags    = implode(',', $contacts->tags);

    // Aqui você serializa o vetor de tags:
    $tags = json_encode($tags);

    // Agora execute a sua *query* de INSERT:
    $query = mysqli_query($conexao, "INSERT INTO leads(nome,tags) VALUES ('$nome','$tags')";

}

And when you read from the database use explode , something like this:

explode(',', $row['tags']);
    
01.02.2017 / 14:26