Senza categoria

Elaborazione Prodotti

Procedura aggiornata al 06/03/2024

a. si importano tutti i prodotti su http://192.168.220.136/wordpress –> ubuntu server locale
a1. Esiste installazione backup al 06/03/2024 del sistema di import nella cartella Ubuntu-Server su drive, basta ripristinarla con Duplicatori Pro
b. Vanno esportati i prodotti nuovi appena creati tramite…
b1. anche le categorie vanno esportate, ma ci vuole un meccanismo che cerchi nuove e vecchie categorie
b2. bisognerebbe anche andare sul database magento e vedere quali sono effettivamente le categorie presenti sul sito

Tramite questa query andiamo a vedere qual’era la categoria di magento e qual è la nuova categoria associata

SELECT tm.meta_value as ID_VECCHIA_CATEGORIA,
t.term_id as ID_CAT_WOOCOMMERCE,
t.name as NOME_CATEGORIA
FROM ed2024_termmeta AS tm
INNER JOIN ed2024_terms AS t ON tm.term_id = t.term_id
WHERE tm.meta_key = '_fgm2wc_old_product_category_id-lang0';

Esportiamo dal database magento tutta la lista di id prodotto, categorie nomi e id

SELECT 
    cpe.entity_id AS 'Product ID', 
    cpev.value AS 'Product Name', 
    GROUP_CONCAT(DISTINCT ccv.value) AS 'Category Names',
    GROUP_CONCAT(DISTINCT ccp.category_id) AS 'Category IDs',
    MAX(ur.request_path) AS 'Product URL'
FROM 
    catalog_product_entity AS cpe
JOIN 
    catalog_product_entity_varchar AS cpev ON cpe.entity_id = cpev.entity_id AND cpev.attribute_id = (SELECT attribute_id FROM eav_attribute WHERE attribute_code = 'name' AND entity_type_id = (SELECT entity_type_id FROM eav_entity_type WHERE entity_type_code = 'catalog_product'))
LEFT JOIN 
    catalog_category_product AS ccp ON cpe.entity_id = ccp.product_id
LEFT JOIN 
    catalog_category_entity_varchar AS ccv ON ccp.category_id = ccv.entity_id AND ccv.attribute_id = (SELECT attribute_id FROM eav_attribute WHERE attribute_code = 'name' AND entity_type_id = (SELECT entity_type_id FROM eav_entity_type WHERE entity_type_code = 'catalog_category'))
LEFT JOIN 
    url_rewrite AS ur ON ur.entity_id = cpe.entity_id AND ur.entity_type = 'product' AND ur.redirect_type = 0 AND ur.store_id = 1
GROUP BY 
    cpe.entity_id, cpev.value;

Si potrebbe realizzare uno script che segue questa logica:
a. controlla le categorie magento al quale è assegnato
b. controlla le categorie Woocommerce al quale è assegnato
c. se il prodotto non è nella categoria viene indirizzato automaticamente

Bisogna riuscire ad esportare tutti gli attributi prodotti

l’installazione finale di woocommerce è gestita su edises-import.digitalfollower.it ma i prodotti e categorie differiscono per id rispetto all’installazione originale perché i prodotti sono stati poi esportati con un tool, questo complica le cose, sarebbe utile capire se possibile cambiare riferimenti a id prodotto e categorie rendendoli identici

a. si esportano i prodotti con export_csv

CREATE TABLE `export_magento` (
  `id_prodotto` bigint(20) unsigned NOT NULL,
  `nome_prodotto` varchar(196) NOT NULL,
  `slug_prodotto` varchar(200) NOT NULL,
  `magento_id` bigint(20) unsigned NOT NULL,
  `autori` text,
  `indice` text,
  `pa_has_cd` varchar(2) DEFAULT NULL,
  `pa_has_gift` varchar(2) DEFAULT NULL,
  `estensioni_web` text,
  `autore` varchar(113) DEFAULT NULL,
  `isbn` varchar(16) DEFAULT NULL,
  `pa_is_ebook` varchar(2) DEFAULT NULL,
  `pa_edizione` varchar(12) DEFAULT NULL,
  `numero_pagine` varchar(49) DEFAULT NULL,
  `pa_stampa` varchar(8) DEFAULT NULL,
  `pa_is_novita` varchar(2) NOT NULL,
  `pa_sfoglia_volume` varchar(2) DEFAULT NULL,
  `pa_is_disponibile` varchar(2) DEFAULT NULL,
  `pa_is_prenotabile` varchar(2) DEFAULT NULL,
  `ricerca_ebook` text,
  `pa_has_software` varchar(2) DEFAULT NULL,
  `sottotitolo` varchar(243) DEFAULT NULL,
  `pa_manuale_compet_sost_anief` varchar(2) DEFAULT NULL,
  `pa_eb_eserc_sost_anief` varchar(2) DEFAULT NULL,
  `pa_in_evidenza` varchar(2) DEFAULT NULL,
  `pa_nopromo` varchar(2) DEFAULT NULL,
  `pa_coupon` varchar(2) DEFAULT NULL,
  `pa_promo20_facebook` varchar(2) DEFAULT NULL,
  `pa_is_vst_ebook` varchar(2) DEFAULT NULL,
  `pa_maestrena` varchar(2) DEFAULT NULL,
  `pa_ripamcoesione` varchar(2) DEFAULT NULL,
  `pa_agenziaentratefb` varchar(2) DEFAULT NULL,
  `pa_man40` varchar(2) DEFAULT NULL,
  `pa_specializzazionimediche` varchar(2) DEFAULT NULL,
  `pa_collanads` varchar(2) DEFAULT NULL,
  `pa_prometheus` varchar(2) DEFAULT NULL,
  `pa_ammissioni` varchar(2) DEFAULT NULL,
  `pa_feedlibrerie` varchar(2) DEFAULT NULL,
  `pa_itastranieri` varchar(2) DEFAULT NULL,
  `pa_mibact` varchar(2) DEFAULT NULL,
  `pa_formato` varchar(20) DEFAULT NULL,
  `pa_scontostanfield` varchar(2) DEFAULT NULL,
  `pa_scontovigili` varchar(2) DEFAULT NULL,
  `pa_in_ebook_search` varchar(2) DEFAULT NULL,
  `pa_has_vst_ppe_ebook` varchar(2) DEFAULT NULL,
  `pa_affiliati_infermieri` varchar(2) DEFAULT NULL,
  `pa_profsanitarielavoro` varchar(2) DEFAULT NULL,
  `pa_infante` varchar(2) DEFAULT NULL,
  `pa_omaggioebook` varchar(2) DEFAULT NULL,
  `pa_kitinfante` varchar(2) DEFAULT NULL,
  `pa_specmedichevito` varchar(2) DEFAULT NULL,
  `pa_cgiltorino` varchar(2) DEFAULT NULL,
  `pa_medprofammissioni` varchar(2) DEFAULT NULL,
  `pa_sconto_aprile_2020` varchar(2) DEFAULT NULL,
  `pa_concorsocattedra100sconto` varchar(2) DEFAULT NULL,
  `pa_verdolina` varchar(2) DEFAULT NULL,
  `pa_codiceds` varchar(2) DEFAULT NULL,
  `pa_sibioc` varchar(2) DEFAULT NULL,
  `pa_escludi_pdf_catalogo` text,
  `pa_scontodisal` varchar(2) DEFAULT NULL,
  `pa_disalsingoli` varchar(2) DEFAULT NULL,
  `pa_is_edigita_ebook` varchar(2) DEFAULT NULL,
  `pa_is_edigita_ebook_ppe` varchar(2) DEFAULT NULL,
  `pa_url_sistema_verifica` varchar(38) DEFAULT NULL,
  `id_prodotto_nuova_versione` varchar(92) DEFAULT NULL,
  `lista_sotto_img` text,
  `pa_vst_ppe_resource_id_prefix` varchar(13) DEFAULT NULL,
  `url_ebook` varchar(242) DEFAULT NULL,
  `data_disponibilita` varchar(19) DEFAULT NULL,
  `errata_corrige` text,
  `codice_prodotto` varchar(9) DEFAULT NULL,
  `vst_resource_id_vbid` varchar(14) DEFAULT NULL,
  `pa_acs_resource_id` varchar(51) DEFAULT NULL,
  `url_cartaceo` varchar(255) DEFAULT NULL,
  `pa_lingua` varchar(8) DEFAULT NULL,
  `pa_versione` varchar(30) DEFAULT NULL,
  `pa_apple_store` varchar(72) DEFAULT NULL,
  `brevi_info` varchar(207) DEFAULT NULL,
  `pa_dispositivi_supportati` varchar(107) DEFAULT NULL,
  `specifiche` text,
  `struttura` text,
  `pa_demo` varchar(59) DEFAULT NULL,
  `pa_docebo_info` varchar(175) DEFAULT NULL,
  `pa_elearning` varchar(2) DEFAULT NULL,
  `pa_docebo_course` varchar(11) DEFAULT NULL,
  `descrizione_per_widget` text,
  `country_of_manufacture` varchar(2) DEFAULT NULL,
  `tag` text,
  `pa_market_android` varchar(73) DEFAULT NULL,
  `id_riferimento_edigita` varchar(15) DEFAULT NULL,
  `pa_edigita_ppe_resource_id` varchar(13) DEFAULT NULL,
  `edizione` varchar(2) DEFAULT NULL,
  `pa_printable_book_cover_url` varchar(11) DEFAULT NULL,
  `pa_cost` varchar(100) DEFAULT NULL,
  `sottotitolo2` varchar(46) DEFAULT NULL,
  `isbn2` text,
  `numero_pagine2` text,
  `tag2` text,
  `codice_prodotto2` text,
  `ricerca_ebook2` text,
  `product_cat` varchar(161) NOT NULL,
  `product_type` varchar(8) NOT NULL,
  `product_visibility` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id_prodotto`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
-- INSERT INTO magento_import (magento_id, isbn)
-- SELECT entity_id, sku
-- FROM catalog_product_entity;

-- UPDATE magento_import mi
-- JOIN wpcv_postmeta wpm ON mi.isbn = wpm.meta_value AND wpm.meta_key = '_sku'
-- JOIN wpcv_posts wp ON wpm.post_id = wp.ID AND wp.post_type = 'product'
-- SET mi.id_woocommerce = wp.ID

-- UPDATE magento_import mi
-- JOIN wpcv_postmeta wpm ON mi.id_woocommerce = wpm.post_id
-- SET mi.kit = 'yes'
-- WHERE wpm.meta_key = '_custom_kit_checkbox'
-- AND wpm.meta_value = 'yes';
Senza categoria

Endpoint EdiSES Oauth2 – Area Riservata

Ambiente di test di auth:
Authorization: https://edisesauth.meetweb.dev/oauth2/authorize
Token: https://edisesauth.meetweb.dev/oauth2/token
Get User Info: https://edisesauth.meetweb.dev/oauth2/userinfo

Client ID: ediseswp_authtest_5423TEST
Client secret: WzfCt2LxqFbpkg2soEmc
Scope: openid
Authorize Endpoint: https://edisesauth.meetweb.dev/oauth2/authorize
Token Endpoint: https://edisesauth.meetweb.dev/oauth2/token
Userinfo Endpoint: https://edisesauth.meetweb.dev/oauth2/userinfo

#######################################################################
 
Gli endpoint dell’ambiente di produzione sono i seguenti:
Authorization: https://auth.edises.it//oauth2/authorize
Token: https://auth.edises.it/oauth2/token
Get User Info: https://auth.edises.it/oauth2/userinfo
 
Qui la documentazione delle specifiche oauth2 https://www.rfc-editor.org/rfc/rfc6749#section-4.

https://areariservataedises.meetweb.dev/purchases-api/doc/

secret JWT 
AJ2pwDCTSamcMR1KxfYSCYrEOXfsioCTWPZcHdzVj6l4t99R3ooOUBYjCqDzmo25T
<?php
/**
 * Plugin Name: Notifica API Area Riservata
 * Plugin URI: https://www.digitalfollowers.com
 * Description: API Notification Area Riservata.
 * Version: 1.3.1
 * Author: Staff - Digital Followers
 * Author URI: https://www.digitalfollowers.com
 */

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

// Aggiungi il box personalizzato alla pagina dell'ordine
add_action('add_meta_boxes', 'wc_add_generate_api_meetweb');
function wc_add_generate_api_meetweb() {
    add_meta_box(
        'wc_add_generate_api',
        __('API Area Riservata', 'wc-generate-xml'),
        'wc_add_generate_api_meetweb_content',
        'shop_order',
        'side',
        'default'
    );
}

// Callback per il contenuto del box
function wc_add_generate_api_meetweb_content($post) {
    $order_id = $post->ID;
    $api_response = get_post_meta($order_id, '_api_response', true);
    $jwt_payload = get_post_meta($order_id, '_jwt_payload', true);
    ?>
    <button id="notify_api_button" class="button button-primary">Invia Notifica API</button>
    <div id="api_response"><pre><?php echo esc_html($api_response); ?></pre></div>
    <h4>Payload JWT</h4>
    <div style="width:250px;height:auto;overflow:scroll;"><pre id="jwt_payload"><?php echo esc_html($jwt_payload); ?></pre></div>
    <script type="text/javascript">
        jQuery(document).ready(function($) {
            $('#notify_api_button').click(function() {
                var orderId = '<?php echo $post->ID; ?>';
                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'notify_api',
                        order_id: orderId,
                    },
                    success: function(response) {
                        $('#api_response').html('<pre>' + JSON.stringify(response, null, 2) + '</pre>');
                        $('#jwt_payload').text(response.jwt_payload);
                        location.reload(); // Ricarica la pagina per vedere i dati salvati
                    },
                    error: function(error) {
                        $('#api_response').html('<pre>' + JSON.stringify(error, null, 2) + '</pre>');
                    }
                });
            });
        });
    </script>
    <?php
}

// Gestisci la richiesta AJAX
add_action('wp_ajax_notify_api', 'notify_api_callback');
function notify_api_callback() {
    $order_id = intval($_POST['order_id']);
    $response = notify_purchase_to_external_api($order_id);
    if (!empty($response['jwt_payload'])) {
        update_post_meta($order_id, '_api_response', wp_json_encode($response));
        update_post_meta($order_id, '_jwt_payload', $response['jwt_payload']);
        error_log('Meta updated for order ' . $order_id . ': success');
        
        $order = wc_get_order($order_id);
        $note = 'API Notification Payload: ' . $response['jwt_payload'];
        $order->add_order_note($note);
    } else {
        error_log('JWT payload missing for order ' . $order_id);
    }
    echo wp_json_encode($response);
    wp_die();
}

// Funzione per notificare l'acquisto all'API esterna
function notify_purchase_to_external_api($order_id) {
    $order = wc_get_order($order_id);
    error_log('notify_purchase_to_external_api called for order ' . $order_id); // Debug log
    $products_data = [];
    
    foreach ($order->get_items() as $item_id => $item) {
        $product = $item->get_product();
        
        // Ottieni l'ID del libro Magento
        $magentoBookId = get_post_meta($product->get_id(), '_magento_id', true);
        if (!$magentoBookId) {
            $magentoBookId = $product->get_id();
        }
        
        // Ottieni enableResources
        $formato = get_post_meta($product->get_id(), 'formato', true);
        $enableResources = in_array($formato, ['eBook', 'Videocorso completo']);

        $products_data[] = [
            'magentoBookId' => $magentoBookId,
            'enableResources' => $enableResources
        ];
    }

    $payload_details = [
     //   'customerId' => (string) $order->get_user_id(), // Ensure customerId is a string
        'customerId' => "698292", // Ensure customerId is a string
        'customerEmail' => $order->get_billing_email(),
//        'customerEmail' => "fabio@digitalfollowers.com",

        'orderId' => (string) $order->get_id(), // Ensure orderId is a string
        'products' => $products_data
    ];

    $signature = 'AJ2pwDCTSamcMR1KxfYSCYrEOXfsioCTWPZcHdzVj6l4t99R3ooOUBYjCqDzmo25T';
    $jwt = generate_jwt($payload_details, $signature);

    // Esegui la chiamata all'API o log per il test
    $response = [];
    if (!is_test_mode()) {
      
     //   $api_response = wp_remote_post('https://areariservataedises.meetweb.dev/api/notify-purchased-products', [ 
     // meetweb api
        $api_response = wp_remote_post('https://www.digitalfollowers.com/api/endpoint-prodotto.php', [
            'body'    => wp_json_encode(['data' => $jwt]),
            'headers' => [
                'Content-Type' => 'application/json',
            ],
        ]);

        if (is_wp_error($api_response)) {
            $response = ['error' => $api_response->get_error_message(), 'jwt_payload' => $jwt];
        } else {
            $response_body = wp_remote_retrieve_body($api_response);
            error_log('API response body: ' . $response_body); // Log the response body for debugging
            error_log('API response code: ' . wp_remote_retrieve_response_code($api_response)); // Log the response code for debugging
            error_log('API response headers: ' . print_r(wp_remote_retrieve_headers($api_response), true)); // Log the response headers for debugging
            if (wp_remote_retrieve_response_code($api_response) == 200) {
                $response = ['message' => 'Notifica inviata con successo', 'jwt_payload' => $jwt];              
                } else {
                $response_body_decoded = json_decode($response_body, true);
                if (is_array($response_body_decoded)) {
                    $response = array_merge($response_body_decoded, ['jwt_payload' => $jwt]);
                } else {
                    $response = ['error' => 'Invalid response body: ' . $response_body, 'jwt_payload' => $jwt];
                }
            }
        }
    } else {
        // Log the payload for testing
        error_log('Test mode: Payload: ' . wp_json_encode(['data' => $jwt]));
        $response = ['message' => 'Test mode: Payload logged', 'jwt_payload' => $jwt];
    }

    // Aggiorna i metadati dell'ordine
    update_post_meta($order_id, '_api_response', $response['message']);
    update_post_meta($order_id, '_jwt_payload', $response['jwt_payload']);

    $order = wc_get_order($order_id);
    $data = date('d/m/y H:i');
    $note = 'API Notification Payload: ' . 'Data/Ora invio: '. $data .'Payload JWT: ' . $response['jwt_payload'];
    $order->add_order_note($note);
    
    error_log('Meta updated for order ' . $order_id . ': success');
    
    return $response;
}

function generate_jwt($payload, $secret) {
    $header = wp_json_encode(['typ' => 'JWT', 'alg' => 'HS512']);
    $base64UrlHeader = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($header));
    $base64UrlPayload = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode(wp_json_encode($payload)));
    $signature = hash_hmac('sha512', $base64UrlHeader . "." . $base64UrlPayload, $secret, true);
    $base64UrlSignature = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($signature));
    return $base64UrlHeader . "." . $base64UrlPayload . "." . $base64UrlSignature;
}

function is_test_mode() {
    return false; // Set to false in production
}

// Esegui la notifica automatica quando lo stato dell'ordine viene impostato su "processing"
add_action('woocommerce_order_status_processing', 'notify_purchase_to_external_api');
?>

Senza categoria

EdiSES – Attributi Grezzi & Completi

<?php
// Connessione al database WooCommerce
$servername = "localhost";
$username = "fabio";
$password = "aaa";
$dbname = "edises_1";
$conn = new mysqli($servername, $username, $password, $dbname);

// Verifica della connessione
if ($conn->connect_error) {
  die("Connessione fallita: " . $conn->connect_error);
}

// Esegui la query per estrarre gli attributi dei prodotti
$sql = "SELECT p.ID as id_prodotto, pm.meta_value as attributi_serializzati
FROM ed2024_posts p
JOIN ed2024_postmeta pm ON p.ID = pm.post_id
WHERE p.post_type = 'product'
  AND pm.meta_key = '_product_attributes'";

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

// Creazione del file CSV
$csvFileName = 'attributi_grezzi.csv';
$csvFile = fopen($csvFileName, 'w');

// Inizializza un array per tenere traccia di tutti i nomi degli attributi
$attributi_header = array('id_prodotto');
$attributi_rows = array();

// Elabora i risultati della query e costruisci l'array degli attributi
if ($result->num_rows > 0) {
  while($row = $result->fetch_assoc()) {
    $attributi = unserialize($row['attributi_serializzati']);
    $attributi_row = array('id_prodotto' => $row['id_prodotto']);
    foreach ($attributi as $nome_attributo => $dettagli_attributo) {
      if (!in_array($nome_attributo, $attributi_header)) {
        $attributi_header[] = $nome_attributo;
      }
      if (isset($dettagli_attributo['value'])) {
        $attributi_row[$nome_attributo] = $dettagli_attributo['value'];
      } elseif (isset($dettagli_attributo['name'])) {
        $attributi_row[$nome_attributo] = $dettagli_attributo['name'];
      }
    }
    $attributi_rows[] = $attributi_row;
  }
} else {
  echo "Nessun risultato trovato";
}

// Scrivi l'intestazione nel file CSV
fputcsv($csvFile, $attributi_header);

// Scrivi i valori degli attributi nel file CSV
foreach ($attributi_rows as $attributi_row) {
  $csvRow = array();
  foreach ($attributi_header as $header) {
    $csvRow[] = isset($attributi_row[$header]) ? $attributi_row[$header] : '';
  }
  fputcsv($csvFile, $csvRow);
}

// Chiudi la connessione al database e il file CSV
$conn->close();
fclose($csvFile);

echo "File CSV creato con successo: " . $csvFileName;
?>

<?php
// Connessione al database WooCommerce
$servername = "localhost";
$username = "fabio";
$password = "aaa";
$dbname = "edises_1";
$conn = new mysqli($servername, $username, $password, $dbname);

// Verifica della connessione
if ($conn->connect_error) {
    die("Connessione fallita: " . $conn->connect_error);
}

// Prima query per estrarre gli attributi dei prodotti
$sql = "SELECT p.ID as id_prodotto, pm.meta_value as attributi_serializzati
        FROM ed2024_posts p
        JOIN ed2024_postmeta pm ON p.ID = pm.post_id
        WHERE p.post_type = 'product' AND pm.meta_key = '_product_attributes'";

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

// Inizializza un array per tenere traccia di tutti i nomi degli attributi
$attributi_header = array('id_prodotto');
$attributi_rows = array();

// Elabora i risultati della prima query e costruisci l'array degli attributi
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $attributi = unserialize($row['attributi_serializzati']);
        $attributi_row = array('id_prodotto' => $row['id_prodotto']);
        foreach ($attributi as $nome_attributo => $dettagli_attributo) {
            if (!in_array($nome_attributo, $attributi_header)) {
                $attributi_header[] = $nome_attributo;
            }
            $attributi_row[$nome_attributo] = $dettagli_attributo['value'] ?? $dettagli_attributo['name'] ?? '';
        }
        $attributi_rows[$row['id_prodotto']] = $attributi_row;
    }
} else {
    echo "Nessun risultato trovato per la prima query";
}

// Seconda query per ottenere informazioni aggiuntive
$sql2 = "SELECT
            t.name AS attribute_name,
            tt.taxonomy AS attribute_taxonomy,
            tr.object_id AS product_id,
            p.post_title AS product_name
         FROM
            ed2024_terms t
         JOIN
            ed2024_term_taxonomy tt ON t.term_id = tt.term_id
         JOIN
            ed2024_term_relationships tr ON tt.term_taxonomy_id = tr.term_taxonomy_id
         JOIN
            ed2024_posts p ON tr.object_id = p.ID
         WHERE
            p.post_type = 'product'
         ORDER BY
            p.ID, tt.taxonomy;";

$result2 = $conn->query($sql2);

// Elabora i risultati della seconda query
if ($result2->num_rows > 0) {
    while($row2 = $result2->fetch_assoc()) {
        $product_id = $row2['product_id'];
        $attribute_taxonomy = $row2['attribute_taxonomy'];
        $attribute_name = $row2['attribute_name'];

        // Aggiungi il nuovo header se non esiste
        if (!in_array($attribute_taxonomy, $attributi_header)) {
            $attributi_header[] = $attribute_taxonomy;
        }

        // Assicurati che l'array per questo prodotto esista
        if (!isset($attributi_rows[$product_id])) {
            $attributi_rows[$product_id] = array('id_prodotto' => $product_id);
        }

        // Aggiorna l'array dei dati del prodotto
        $attributi_rows[$product_id][$attribute_taxonomy] = $attribute_name;
    }
} else {
    echo "Nessun risultato trovato per la seconda query";
}

// Creazione del file CSV
$csvFileName = 'attributi_completi.csv';
$csvFile = fopen($csvFileName, 'w');

// Scrivi l'intestazione nel file CSV
fputcsv($csvFile, $attributi_header);

// Scrivi i valori degli attributi nel file CSV
foreach ($attributi_rows as $product_id => $attributi_row) {
    $csvRow = array();
    foreach ($attributi_header as $header) {
        $csvRow[] = $attributi_row[$header] ?? '';
    }
    fputcsv($csvFile, $csvRow);
}

// Chiudi la connessione al database e il file CSV
$conn->close();
fclose($csvFile);

echo "File CSV creato con successo: " . $csvFileName;
?>
Senza categoria

UBUNTU 23.10 CONFIG MySQL/MariaDB

sudo apt update

sudo apt install mysql-server
sudo apt install mariadb-server

sudo mysql_secure_installation

sudo systemctl status mysql
sudo systemctl stop mysql / sudo systemctl restart mysql

sudo mysql -u root -p
CREATE USER 'fabio'@'%' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON *.* TO 'fabio'@'%';
FLUSH PRIVILEGES;

[Permettere connessioni da esterno]

sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf
bind-address = 0.0.0.0

sudo apt install nautilus-share
nautilus -q

sudo gpasswd --add $USER sambashare

sudo smbpasswd -a $USER

[riavvia il server per rendere effettive le modifiche]
[cambio user]

sed -i 's/edises-mage-usr/fabio/g' edises-backup-completo.sql
oppure
sed -i 's/edises-mage-usr/username-db-produzione/g' edises-backup-completo.sql

sed -i 's/DEFINER=`fabio`@`%`/DEFINER=`dsiqifol_magento`@`%`/g' edises-backup-completo.sql 

[controllo utente]
grep -o '/*!50017 DEFINER=`dsiqipof_magento`@`%`*/' dump_database_mariadb.sql | wc -l
[gxibghvy_mg2 o username db produzione]
grep -o 'DEFINER=`
dsiqipof_magento`@`%`' dump_database_mariadb.sql | wc -l

va eliminato /*!50017 DEFINER=`dsiqipof_magento`@`%`*/


[ripristino backup corrotto direttamente saltando errori]
mysql -u fabio -p -f -D nome-database < /home/fabio/Scrivania/DB/edises-backup-originale.sql 2> /home/fabio/Scrivania/log_import.txt

[export backup]

esporta con Antares SQL e importa con lo stesso software

[oppure]

mariadb-dump -u fabio -p --default-character-set=utf8mb4 --skip-set-charset --add-drop-database mag2 > /home/fabio/Scrivania/DB/dump_database_mariadb2.sql 2> /home/fabio/Scrivania/DB/error.log

import con MySQL Workbench

sed -i 's/DEFINER=`fabio`@`%`/DEFINER=`dsiqipof`@`localhost`/g' edises-backup-completo.sql 
WordPress

Pulire database WordPress/WooCommerce

Questa è una query SQL che seleziona tutte le colonne dalla tabella “wpgy_users” in cui la colonna “ID” è presente in una subquery che seleziona “user_id” dalla tabella “wpgy_usermeta” dove “meta_key” è uguale a ‘first_name’ e “meta_value” è nullo o vuoto. In sostanza, la query restituisce tutti gli utenti nella tabella “wpgy_users” che non hanno un valore presente nella colonna “first_name” della tabella “wpgy_usermeta”.

SELECT * FROM `wpgy_users`
WHERE `ID` IN (SELECT `user_id` FROM `wpgy_usermeta` WHERE `meta_key` = 'first_name' AND (`meta_value` IS NULL OR `meta_value` = ''));

Questa query elimina gli utenti dalla tabella wpgy_users che non hanno un nome impostato nel loro profilo utente (campo “first_name” della tabella wpgy_usermeta). Si consiglia di eseguire un backup dei dati prima di eseguire questa query.

DELETE FROM `wpgy_users`
WHERE `ID` IN (SELECT `user_id` FROM `wpgy_usermeta` WHERE `meta_key` = 'first_name' AND (`meta_value` IS NULL OR `meta_value` = ''));

Questa è una query SQL che seleziona tutte le colonne dalla tabella “wpgy_usermeta” dove la colonna “user_id” non è presente nella subquery che seleziona “ID” dalla tabella “wpgy_users” e la colonna “user_id” è presente in una subquery che seleziona “user_id” dalla tabella “wpgy_usermeta” dove “meta_key” è uguale a ‘first_name’ e “meta_value” è nullo o vuoto. In pratica, la query restituisce tutti i record nella tabella “wpgy_usermeta” che hanno un valore nullo o vuoto nella colonna “first_name” e non sono presenti nella tabella “wpgy_users”.

SELECT * FROM `wpgy_usermeta`
WHERE `user_id` NOT IN (SELECT `ID` FROM `wpgy_users`)
  AND `user_id` IN (SELECT `user_id` FROM `wpgy_usermeta` WHERE `meta_key` = 'first_name' AND (`meta_value` IS NULL OR `meta_value` = ''));

Questa query SQL elimina i meta-dati degli utenti che non esistono nella tabella wpgy_users e che non hanno un nome impostato nel loro profilo utente dalla tabella wpgy_usermeta:

DELETE FROM `wpgy_usermeta`
WHERE `user_id` NOT IN (SELECT `ID` FROM `wpgy_users`)
  AND `user_id` IN (SELECT `user_id` FROM `wpgy_usermeta` WHERE `meta_key` = 'first_name' AND (`meta_value` IS NULL OR `meta_value` = ''));