Handsontable's datas to sql database

2.5k views Asked by At

I'm a beginner at javascript and I'm a little lost in all that stuff.

I want all the data from my handsontable pushed in my sql database. I follow the examples given by handsontable, but it doesn't work.

Here is the code, where I create my handsontable :

`

$(document).ready(function () {

var container = document.getElementById('Grille_competences');

var headerRenderer = function (instance, td, row, col, prop, value,
cellProperties) {
Handsontable.renderers.TextRenderer.apply(this, arguments);
td.style.fontWeight = 'bold';
td.style.textAlign = 'center';
td.style.backgroundColor = '#B0C4DE';
};

//Initialisation des données de la grille.
var data = [["Compétences","Description","Code",""],
        ["", "", "",""],
        ["","", "",""],
        ["","", "",""],
        ["","", "",""],
        ["","", "",""]];

//Création de la grille
hot = new Handsontable(container, {
data: data,
height: 800,
width: 1183,
colWidths: [35,200,25,80],
manualRowResize: true,
colHeaders: true,
rowHeaders: true,
mergeCells: true,
stretchH: 'all',
columnSorting: true,
contextMenu: true,    
contextMenuCopyPaste: {
  swfPath: './zeroclipboard/dist/ZeroClipboard.swf'
},


//Fonctionnalités lors d'un clic droit dans la grille.

 contextMenu: {    

   items: {
    "row_above": {
        name: 'Insérer ligne au dessus',
      disabled: function () {            
        return hot.getSelected()[0] === 0;
      }
    },
    "row_below": {
        name: 'Insérer ligne en dessous',
        disabled: function() {            
        return hot.getSelected()[0] === 0;
    }
  },
    "hsep1": "---------",
    "col_left": {
        name: 'Insérer colonne à gauche',
        disabled: function () {
          return hot.getSelected()[0] === 0;
        }
    },
    "col_right": {
        name: 'Insérer colonne à droite',
        disabled: function() {
          return hot.getSelected()[0] === 0;
        }
    },
    "hsep2": "---------",
    "remove_row": {
      name: 'Supprimer la ligne',
      disabled: function () {
        return hot.getSelected()[0] === 0;
      }
    },

    "remove_col": {
      name: 'Supprimer la colonne',
      disabled: function () {
        return hot.getSelected()[0] === 0;
      }
    },
    "hsep3": "---------",
    "copy": {
      name:'Copier',
      disabled: function () {
        return hot.getSelected()[0] === 0;
      }
    },
    "paste": {
      name: 'Coller',
      disabled: function(){
        return hot.getSelected()[0] === 0;
      }
    },
    "hsep4": "---------",
    "undo": {
      name:'Précédent',
      disabled: function(){
        return hot.getSelected()[0] === 0;
      }
    },
    "redo": {
      name: 'Suivant',
      disabled: function(){
        return hot.getSelected()[0] === 0;
      }
    },
    "hsep5": "---------",
    "make_read_only": {
      name: 'Lecture seule',
      disabled: function() {
        return hot.getSelected()[0] === 0;
      }
    },
    "alignment": {
      name: 'Alignement du texte',
      disabled: function () {
        return hot.getSelected()[0] === 0;        
      }          
    },
    "mergeCells": {
      name: 'Fusionner les cellules',
      disabled: function () {
        return hot.getSelected()[0] === 0;
      }
    },


    },
},


//Entetes de la grille en lecture seule. 
cells: function(row, col, prop) {
var cellProperties = {};
if(row===0){
cellProperties.renderer = headerRenderer;
}   
if(row === 0 && col <3){
       cellProperties.readOnly = true;
       }
return cellProperties;
}
});

//Lors d'un clic sur le bouton valider, transmission des données de la grille.


});

 $('#save').click(function(){
   $.ajax({
   url: "testGetData.php",
   dataType: 'json',
   data: {data: hot.getData() }, 
   type: 'GET',
   success: function () {
   $console.text('Saved !');
   }
  });  
});

`

And here is the code for the testGetData.php file :

<?php

session_start();
require_once('./lib/demo/php/functions.php');


$db = getConnection();
createBDD($db);

if($db)
{

$db = new PDO('mysql:host=localhost; dbname=bdd'.$_SESSION['login'],'root', 'passwd');


  createTableBDD($db);


    foreach ($_GET['data'] as $value){
        $query = $db->prepare('INSERT INTO Competences(libelle) VALUES('.$value[0].')');
        $query->execute();

    }

}

?>

If I understand, the handsontable send a $_REQUEST to testGetData.php. So, I can access to the $_GET superglobal. Considering that this variable is an array of many arrays, the $value in the foreach coincide with one of the arrays. But I don't understand why nothing is pushed. I modify the getConnection() function for my sql database.

1

There are 1 answers

3
Carsten Massmann On

I don't know what you are trying to do with createTableBDD($db);. Are you trying to create a new table each time this page is called? You should create the table only once (maybe in phpmyadmin) like

CREATE TABLE cm (id int auto_increment primary key, a int NULL, b int NULL, c int NULL )

and then in the .php file do the following:

// connect to the database:
$p=new PDO("mysql:host=localhost; dbname=$dbname",$uname,$DBpassword);

// in order to demonstrate the back-end without the handson front-end
// I just generate some sample data (6 rows, 3 columns) into array $data:
for ($i=100;$i<700;$data[]=$b,$i+=100) for ($b=array(),$j=1;$j<4;$j++) $b[]=$i+$j;
// this would otherwise come from: $data=$_GET['data'];

// prepare the INSERT statement ONLY ONCE:
$ins=$p->prepare("INSERT INTO cm(a,b,c) VALUES(?,?,?)");

// and run it for each line of the $data array:
foreach ($data as $a) $ins->execute($a);

You might find this tutorial helpful in getting started with PDO: http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers#Running_Simple_INSERT.2C_UPDATE.2C_or_DELETE_statements

Please note that this solution will only work for $data arrays with exactly 3 columns. Your handson table in the front-end might supply any numer of columns. Therefore it is up to you to make sure the number of columns is correct before you INSERT the data.