Insert array into database

Asked

Viewed 1,875 times

-3

I didn’t post the entire code before because it was too extensive (I’ve summarized it by taking some irrelevant data), now it’s the entire code. I’m taking values from the products, I run a foreach picking up the ID of each one and then pull the data from that product, when it arrives in 'categoria'=>$produto_loaded->getCategoryIds(), it brings me an array of numbers because the product is in several categories, when I will insert this array again in the table as below it inserts only the name Array.

Code

    ini_set("display_errors", 1);
    ini_set('memory_limit','1024M');
        require_once('app/Mage.php');
        Mage::app(0);


        $collection = Mage::getModel('catalog/product')->getCollection();

        foreach ($collection as $key => $produto) {
        $id = $produto->getId();

        $produto_loaded = Mage::getModel('catalog/product')->load($id);

            $tudo = array(

            'categoria'=>$produto_loaded->getCategoryIds(),
            'positioncat'=>$produto_loaded->getPosition(),
            'loja'=>addslashes($produto_loaded->getStoreId()),
            'atributo_id'=>addslashes($produto_loaded->getAttributeSetId()), 
            'tipo_de_produto'=>addslashes($produto_loaded->getTypeID()),
            'id_produto' =>addslashes($produto_loaded->getId()), 
            'sku'=>addslashes($produto_loaded->getSku()),
            'status'=>addslashes($produto_loaded->getStatus()),
            'visibilidade'=>addslashes($produto_loaded->getVisibility()),
            'nome'=>addslashes($produto_loaded->getName()),
            'descriçao'=>addslashes($produto_loaded->getDescription()),
            'nomeurl'=>addslashes($produto_loaded->getProductUrl()));

                    $teste = $tudo['id_produto'];
                    $link = mysqli_connect('localhost','root','','teste2');
                    $link->set_charset("utf8");
                    $query = 

                            "SELECT a.website_id as websiteid, 
                            b.category_id as categoria, 
                            b.position as positioncat
                            FROM catalog_product_website a
                            INNER JOIN catalog_category_product b
                            ON a.product_id = b.product_id
                            WHERE a.product_id = '$teste'";

                    $select = mysqli_query($link, $query);
                    while ($row = mysqli_fetch_array($select)) {
                       $websiteid = $row['websiteid'];
                    }

        if($produto_loaded->getTypeId() == 'bundle'){

                    $teste = $tudo['id_produto'];
                    $link = mysqli_connect('localhost','root','','teste2');
                    $link->set_charset("utf8");
                    $query = "SELECT selection_id as select_id, option_id as option_bundle, position as position_bundle, parent_product_id as bundle_id, product_id as prod_id, is_default as padrao, selection_price_type as tipodepreco, selection_price_value as preco_bundle, selection_qty as qtd, selection_can_change_qty as mudarqtd from catalog_product_bundle_selection WHERE parent_product_id = '$teste'";
                    $select = mysqli_query($link, $query);
                    foreach($select as $s){
                        $connection = Mage::getSingleton('core/resource')->getConnection('core_write');
                        $query = "INSERT INTO produtos (`loja`, `websiteid`, `atributo_id`, `tipo_de_produto`,  `id_produto`,  `sku`, `status`, `visibilidade`, `nome`, `descriçao`, `nomeurl`, `categoria`,) VALUES ('".$tudo['loja']."', '".$websiteid."',  '".$tudo['atributo_id']."', '".$tudo['tipo_de_produto']."',  '".$tudo['id_produto']."',  '".$tudo['sku']."', '".$tudo['status']."', '".$tudo['visibilidade']."', '".$tudo['nome']."', '".$tudo['descriçao']."', '".$tudo['nomeurl']."', '".$tudo['categoria']."', '".$s['bundle_id']."', '".$s['prod_id']."', '".$s['position_bundle']."', '".$s['option_bundle']."', '".$s['select_id']."', '".$s['padrao']."', '".$s['tipodepreco']."', '".$s['preco_bundle']."', '".$s['qtd']."', '".$s['mudarqtd']."')";
                        $connection->query($query);
                    }

                } else {
                    $connection = Mage::getSingleton('core/resource')->getConnection('core_write');
                    $query = "INSERT INTO produtos (`loja`, `websiteid`, `atributo_id`, `tipo_de_produto`, `id_produto`,  `sku`, `status`, `visibilidade`, `nome`, `descriçao`, `nomeurl`, `categoria`) VALUES ('".$tudo['loja']."', '".$websiteid."', '".$tudo['atributo_id']."', '".$tudo['tipo_de_produto']."', '".$tudo['id_produto']."',  '".$tudo['sku']."', '".$tudo['status']."', '".$tudo['visibilidade']."', '".$tudo['nome']."', '".$tudo['descriçao']."', '".$tudo['nomeurl']."', '".$tudo['categoria']."')";
                    $connection->query($query);
                  }
                }
                ?>
  • 1

    You are probably saving the array as a whole, and not taking the data from each position. Put the code that does that insert

  • 1

    You’ll get better answers if you give people code they can use to reproduce the problem

  • I updated the question with more information, if you need any additional information just ask!

  • It would be better to turn this Array in JSON

  • how many columns are in the table?

  • I’ll rephrase the question

  • is a product with several categories?

  • I edited the question, see if it helps.

  • But do you want to update a product or insert a new one? Or do you just want to insert the categories into an existing product, or is it all created on time?

  • I’m making a change from an old bank, I want to take all products with their categories and insert in another bank, then I take all this to a table and then insert in the new bank

Show 5 more comments

2 answers

1

Scroll through your array to enter the records correctly:

foreach($tudo['categoria'] as $idCategoria){
    $query = "INSERT INTO produtos (`categoria`, .........) VALUES ('".$idCategoria."', .........)";
}

0

If your table columns are shown in your matrix keys, you can insert it this way.

foreach ($tudo as $column => $value) {
   $cols[] = $column;
   $vals[] =  $value;
   //quando necessário troque a linha de cima pela de baixo
   //$vals[] = mysqli_real_escape_string($link, $value);
}
$colnames = "`".implode("`, `", $cols)."`";
$colvals = "'".implode("', '", $vals)."'";

$mysql = mysqli_query($link, "INSERT INTO produtos ($colnames) VALUES ($colvals)") or die('Database Connection Error ('.mysqli_errno(produtos).') '.mysqli_error(produtos). " on query: INSERT INTO produtos ($colnames) VALUES ($colvals)");

Browser other questions tagged

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