save.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. /**
  3. * This is an example code that shows how you can save Handsontable data on server using PHP with PDO (SQLite).
  4. * This code is not intended to be maximally efficient nor safe. It is for demonstrational purposes only.
  5. * Changes and more examples in different languages are welcome.
  6. *
  7. * Copyright 2012, Marcin Warpechowski
  8. * Licensed under the MIT license.
  9. * http://github.com/handsontable/handsontable/
  10. */
  11. require_once('functions.php');
  12. try {
  13. //open the database
  14. $db = getConnection();
  15. createCarsTable($db);
  16. $colMap = array(
  17. 0 => 'manufacturer',
  18. 1 => 'year',
  19. 2 => 'price'
  20. );
  21. if (isset($_POST['changes']) && $_POST['changes']) {
  22. foreach ($_POST['changes'] as $change) {
  23. $rowId = $change[0] + 1;
  24. $colId = $change[1];
  25. $newVal = $change[3];
  26. if (!isset($colMap[$colId])) {
  27. echo "\n spadam";
  28. continue;
  29. }
  30. $select = $db->prepare('SELECT id FROM cars WHERE id=? LIMIT 1');
  31. $select->execute(array(
  32. $rowId
  33. ));
  34. if ($row = $select->fetch()) {
  35. $query = $db->prepare('UPDATE cars SET `' . $colMap[$colId] . '` = :newVal WHERE id = :id');
  36. } else {
  37. $query = $db->prepare('INSERT INTO cars (id, `' . $colMap[$colId] . '`) VALUES(:id, :newVal)');
  38. }
  39. $query->bindValue(':id', $rowId, PDO::PARAM_INT);
  40. $query->bindValue(':newVal', $newVal, PDO::PARAM_STR);
  41. $query->execute();
  42. }
  43. } elseif (isset($_POST['data']) && $_POST['data']) {
  44. $select = $db->prepare('DELETE FROM cars');
  45. $select->execute();
  46. for ($r = 0, $rlen = count($_POST['data']); $r < $rlen; $r++) {
  47. $rowId = $r + 1;
  48. for ($c = 0, $clen = count($_POST['data'][$r]); $c < $clen; $c++) {
  49. if (!isset($colMap[$c])) {
  50. continue;
  51. }
  52. $newVal = $_POST['data'][$r][$c];
  53. $select = $db->prepare('SELECT id FROM cars WHERE id=? LIMIT 1');
  54. $select->execute(array(
  55. $rowId
  56. ));
  57. if ($row = $select->fetch()) {
  58. $query = $db->prepare('UPDATE cars SET `' . $colMap[$c] . '` = :newVal WHERE id = :id');
  59. } else {
  60. $query = $db->prepare('INSERT INTO cars (id, `' . $colMap[$c] . '`) VALUES(:id, :newVal)');
  61. }
  62. $query->bindValue(':id', $rowId, PDO::PARAM_INT);
  63. $query->bindValue(':newVal', $newVal, PDO::PARAM_STR);
  64. $query->execute();
  65. }
  66. }
  67. }
  68. $out = array(
  69. 'result' => 'ok'
  70. );
  71. echo json_encode($out);
  72. closeConnection($db);
  73. }
  74. catch (PDOException $e) {
  75. print 'Exception : ' . $e->getMessage();
  76. }
  77. ?>