IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

PHP & Base de données Discussion :

Insertion données en BdD


Sujet :

PHP & Base de données

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre averti
    Homme Profil pro
    Étudiant
    Inscrit en
    Septembre 2015
    Messages
    14
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 51
    Localisation : France, Bouches du Rhône (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Septembre 2015
    Messages : 14
    Par défaut Insertion données en BdD
    bonjour

    j'ai retouche un code pour inserer un .csv dans du sql mais quand je tente de les rentrer dans la bdd j'ai des erreurs incomprehensibles

    par contre lorsque je désactive les modules de la base de données , j'ai un retour de tableau correct

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    array(4) {
    [0]=>
    array(3) {
    [0]=>
    string(6) "ggg"
    [1]=>
    string(3) "ttt"
    [2]=>
    string(2) "54"
    }
    [1]=>
    array(3) {
    [0]=>
    string(4) "bbbb"
    [1]=>
    string(3) "fff"
    [2]=>
    string(2) "21"
    }
    [2]=>
    array(3) {
    [0]=>
    string(3) "ggg"
    [1]=>
    string(3) "kkk"
    [2]=>
    string(2) "78"
    }
    [3]=>
    array(3) {
    [0]=>
    string(3) "jjj"
    [1]=>
    string(3) "sss"
    [2]=>
    string(2) "44"
    }
    }
    voici le code :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    <?php
    $filename = 'amazon-fours.csv';
     
    // The nested array to hold all the arrays
    $the_big_array = [];
     
    // Open the file for reading
    if (($h = fopen("{$filename}", "r")) !== FALSE)
    {
    // Each line in the file is converted into an individual array that we call $data
    // The items of the array are comma separated
    while (($data = fgetcsv($h, 0, ";")) !== FALSE)
    {
    // Each individual array is being pushed into the nested array
    $the_big_array[] = $data;
    }
     
    // Close the file
    fclose($h);
    }
     
    include("db_connect.php");
     
    // module d'enregistrement #1
     
    mysqli_query($conn,'LOAD DATA LOCAL INFILE \'amazon-fours.csv\' INTO TABLE produits
    FIELDS TERMINATED BY \';\'
    ENCLOSED BY \'"\'
    LINES TERMINATED BY \'\n\' ')
    or die("Erreur mise à jour table : ".mysqli_error($conn));
     
     
    /*
    // module d'enregistrement #2
    
    $data = [
    'name' => $the_big_array[1],
    'description' => $the_big_array[2],
    'prix' => $the_big_array[3]
    ];
    $sql = "INSERT INTO file VALUES (NULL,:name,:description,:prix)";
    $stmt= $conn->prepare($sql);
    $stmt->execute($data);
    
    // afficher le code
    echo "<pre>";
    var_dump($the_big_array);
    echo "</pre>";
    */
    ?>
     
    db_connect.php
     
    <?php
    $server = "localhost";
    $username = "*******";
    $password = "*******";
    $db = "*********";
    $conn = mysqli_connect($server, $username, $password, $db);
    session_start();
    $_SESSION[`connect`] = $conn ;
    ?>
    j'ai essayé par le module d'enregistrement #1 mais j'ai cette erreur :

    Erreur mise à jour table : You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '$the_big_array[] INTO TABLE produits FIELDS TERMINATED BY ';' ENCLOSED BY...' at line 1
    j'ai donc essayé la module d'enregistrement #2

    mais la aussi j'ai un message d'erreur :
    Warning: Trying to access array offset on value of type bool in /home/u320889525/domains/best-products.fr/public_html/importcsv.php on line 34
    Warning: Trying to access array offset on value of type bool in /home/u320889525/domains/best-products.fr/public_html/importcsv.php on line 35
    Warning: Trying to access array offset on value of type bool in /home/u320889525/domains/best-products.fr/public_html/importcsv.php on line 36
    Fatal error: Uncaught Error: Call to a member function execute() on bool in /home/u320889525/domains/best-products.fr/public_html/importcsv.php:40 Stack trace: #0 {main} thrown in /home/u320889525/domains/best-products.fr/public_html/importcsv.php on line 40
    nb : j'ai verifié db_connect la connection est bonne j'ai bien le echo en retour

    version php ; 8.0

  2. #2
    Expert confirmé
    Avatar de Séb.
    Profil pro
    Inscrit en
    Mars 2005
    Messages
    5 315
    Détails du profil
    Informations personnelles :
    Âge : 47
    Localisation : France

    Informations professionnelles :
    Secteur : High Tech - Opérateur de télécommunications

    Informations forums :
    Inscription : Mars 2005
    Messages : 5 315
    Billets dans le blog
    17
    Par défaut
    j'ai essayé par le module d'enregistrement #1 mais j'ai cette erreur :

    Erreur mise à jour table : You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '$the_big_array[] INTO TABLE produits FIELDS TERMINATED BY ';' ENCLOSED BY...' at line 1
    Le code que tu montres ne peut pas produire cette erreur.

    j'ai donc essayé la module d'enregistrement #2
    Tu fais :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    $data = [
    'name' => $the_big_array[1],
    'description' => $the_big_array[2],
    'prix' => $the_big_array[3]
    ];
    $sql = "INSERT INTO file VALUES (NULL,:name,:description,:prix)";
    $stmt= $conn->prepare($sql);
    $stmt->execute($data);
    Or ça ne fonctionne pas de cette manière (et puis $the_big_array n'est pas construit comme tu as l'air de le croire, avec 1 colonne CSV par entrée, mais avec 1 ligne CSV par entrée).

    Il faut appeler INSERT autant de fois qu'il y a d'entrées dans $the_big_array en parcourant $the_big_array avec foreach().


    PS : il vaut mieux éviter le gras sur le texte "normal" de ton post

  3. #3
    Membre averti
    Homme Profil pro
    Étudiant
    Inscrit en
    Septembre 2015
    Messages
    14
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 51
    Localisation : France, Bouches du Rhône (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Septembre 2015
    Messages : 14
    Par défaut suite
    j'ai teste en mettant des foreach

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
     require_once("db_connect.php");
      foreach ( $the_big_array as $ligne) {  
       foreach ( $ligne as $value) {   
       $data_ = [
       'name' => $value,
       'description' => $value,
       'price' => $value,
       ];
       $sql = "INSERT INTO produits (name,description,price)  VALUES (:name, :description, :price)";
       $stmt= $conn->prepare($sql);
       $stmt->execute($data_);
     
         echo'<br/>value <br/>';
         echo $value;
     
       }   //fin foreach 
      }   //fin foreach 
    }     //fin if isset
     
         echo '<br/>sql <br/>';
         echo $sql;
    ce qui donne en retour :

    Fatal error: Uncaught Error: Call to a member function execute() on bool in /home/u320889525/domains/............../public_html/.............php:33
    Stack trace:
    #0 {main} thrown in /home/u320889525/domains/................/public_html/............php on line 33

    ( $stmt->execute($data_); )
    si je désactive cette ligne j'ai ceci en echo :

    Connexion réussie

    value

    toutes les values ressortent

    sql
    INSERT INTO produits (name,description,price) VALUES (:name, :description, :price)
    ce qui prouve que le problème vient du insert

  4. #4
    Expert confirmé
    Avatar de Séb.
    Profil pro
    Inscrit en
    Mars 2005
    Messages
    5 315
    Détails du profil
    Informations personnelles :
    Âge : 47
    Localisation : France

    Informations professionnelles :
    Secteur : High Tech - Opérateur de télécommunications

    Informations forums :
    Inscription : Mars 2005
    Messages : 5 315
    Billets dans le blog
    17
    Par défaut
    Non le problème vient de la manière dont tu structures tes données et comment tu utilises ta requête préparée.

    Fais simple pour commencer, laisse tomber la requête préparée et le big_array inutile, et reprend les bases.

    Insertion de chaque ligne de ton CSV en base :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    $fp = fopen($file, 'r');
    while ($entry = fgetcsv($fp)) { 
        $sql = <<<SQL
            INSERT INTO products
            SET
                name = {$pdo->quote($entry[0])},
                description = {$pdo->quote($entry[1])},
                price = {$pdo->quote($entry[2])}
            SQL;
        $pdo->exec($sql);
    }
    Quand t'arriveras à faire tourner ça tu pourras ajouter la préparation et une transaction pour accélérer le processus.

  5. #5
    Membre averti
    Homme Profil pro
    Étudiant
    Inscrit en
    Septembre 2015
    Messages
    14
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 51
    Localisation : France, Bouches du Rhône (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Septembre 2015
    Messages : 14
    Par défaut suite
    en remplacant $poe par le $conn de ma connection j'ai cette erreur
    Warning: Undefined array key 1 in /home/u320889525/domains/........../public_html/..............php on line 10 ( description = {$conn->quote($entry[1])}, )
    Warning: Undefined array key 2 in /home/u320889525/domains/........../public_html/.............php on line 11 ( price = {$conn->quote($entry[3])} )
    qui se repete 4 fois

    ( bizarrement pas d'erreurs sur le : name = {$conn->quote($entry[0])},)

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    <?php
    $filename = 'amazon-fours.csv';
    $fp = fopen($filename, 'r');
    require_once("db_connect.php");
    while ($entry = fgetcsv($fp)) {
       $sql = <<<SQL
       INSERT INTO produits
       SET
       name = {$conn->quote($entry[0])},
       description = {$conn->quote($entry[1])},
       price = {$conn->quote($entry[2])}
       SQL;
       $conn->exec($sql);
       } // fin while
    ?>

  6. #6
    Expert confirmé
    Avatar de Séb.
    Profil pro
    Inscrit en
    Mars 2005
    Messages
    5 315
    Détails du profil
    Informations personnelles :
    Âge : 47
    Localisation : France

    Informations professionnelles :
    Secteur : High Tech - Opérateur de télécommunications

    Informations forums :
    Inscription : Mars 2005
    Messages : 5 315
    Billets dans le blog
    17
    Par défaut
    Regarde le contenu de $entry

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. probleme insertion BDD MySQL
    Par myssonuds dans le forum Général Python
    Réponses: 1
    Dernier message: 20/07/2011, 10h33
  2. Probleme insertion image BDD / php
    Par jesaye dans le forum EDI, CMS, Outils, Scripts et API
    Réponses: 4
    Dernier message: 17/06/2011, 10h26
  3. Probleme Insertion dans BDD avec dbaccess
    Par Mobybic dans le forum Bases de données
    Réponses: 4
    Dernier message: 08/03/2011, 20h14
  4. Insertion en double dans ma bdd
    Par n@n¤u dans le forum Hibernate
    Réponses: 13
    Dernier message: 20/07/2007, 15h33

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo