我在尝试将数据从我的handontable表发送到我的SQL数据库(phpMyAdmin)时遇到了麻烦。此表中的数据由用户输入,当他们单击发送时,它将所有数据插入到我的数据库中的现有表中。此外,如果他们单击加载,它将加载他们保存到的数据库中的所有行。我目前正在使用以下脚本尝试将数据发送到我的数据库。
index.php(相关代码):
<!DOCTYPE html>
<html>
<head>
<title>SuburbMap</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="http://code.jquery.com/jquery-1.12.0.js"></script>
<script src="http://docs.handsontable.com/0.16.0/bower_components/handsontable/dist/handsontable.full.js"></script>
<link type="text/css" rel="stylesheet" href="http://docs.handsontable.com/0.16.0/bower_components/handsontable/dist/handsontable.full.min.css">
<script src="http://docs.handsontable.com/0.16.0/bower_components/numeraljs/languages/de.js"></script>
<link rel="stylesheet" type="text/css" href="assets/admin-tools/admin-plugins/admin-panels/adminpanels.css">
<link rel="stylesheet" type="text/css" href="assets/admin-tools/admin-forms/css/admin-forms.css">
<link rel="shortcut icon" href="assets/img/favicon.ico">
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
<![endif]-->
<Style>
#loader {
z-index:99999;
position: fixed;
top: 50%; left: 50%;
transform: translate(-50%, -50%);
}
body {
background-color: white;
margin: 20px;
}
h2 {
margin: 20px 0;
}
.handsontable-table {
overflow: scroll;
position: absolute;
top: 0px;
bottom: 54px;
width: 100%;
}
</style>
</head>
<body>
<div id="example1" class="dataTable"></div>
<p>
<button name="load" id="load">Load</button>
<button name="save" id="save">Save</button>
<label><input type="checkbox" name="autosave" id="autosave" checked="checked" autocomplete="off"> Autosave</label>
</p>
<script>
var
$container = $("#example1"),
$console = $("#exampleConsole"),
$parent = $container.parent(),
autosaveNotification;
$container.handsontable({
startRows: 8,
startCols: 3,
rowHeaders: true,
colHeaders: ['First Name', 'Last Name', 'Email', 'District/Suburb', 'Zip/Postcode', 'Income', 'No. Items', 'Item/Job Description'],
columns: [
{},
{},
{},
{},
{},
{},
{},
{}
],
minSpareCols: 0,
minSpareRows: 1,
contextMenu: true,
contextMenu: {
callback: function(key, options) {
var m = "clicked: " + key;
window.console && console.log(m) || alert(m);
},
items: ['row_above', 'row_below', 'remove_row', 'undo', 'redo', 'copy', 'paste'],
contextMenuCopyPaste: {
swfPath: '/managers/handsontable/dist/ZeroClipboard.swf'
}
},
afterChange: function (change, source) {
if (source === 'loadData') {
return; //don't save this change
}
if ($parent.find('input[name=autosave]').is(':checked')) {
clearTimeout(autosaveNotification);
$.ajax({
url: "/managers/save.php",
dataType: "json",
type: "POST",
data: {changes: change}, //contains changed cells' data
success: function () {
$console.text('Autosaved (' + change.length + ' cell' + (change.length > 1 ? 's' : '') + ')');
autosaveNotification = setTimeout(function () {
$console.text('Changes will be autosaved');
}, 1000);
}
});
}
}
});
var handsontable = $container.data('handsontable');
$parent.find('button[name=save]').click(function () {
$.ajax({
url: "/managers/save.php",
data: {"data": handsontable.getData()}, //returns all cells' data
dataType: 'json',
type: 'POST',
success: function (res) {
if (res.result === 'ok') {
$console.text('Data saved');
}
else {
$console.text('Save error');
}
},
error: function () {
$console.text('Save error');
}
});
});
$parent.find('button[name=reset]').click(function () {
$.ajax({
url: "/managers/reset.php",
success: function () {
$parent.find('button[name=load]').click();
},
error: function () {
$console.text('Data reset failed');
}
});
});
$parent.find('input[name=autosave]').click(function () {
if ($(this).is(':checked')) {
$console.text('Changes will be autosaved');
}
else {
$console.text('Changes will not be autosaved');
}
$parent.find('button[name=load]').click(function () {
$.ajax({
url: "/load.php",
dataType: 'json',
type: 'GET',
success: function (res) {
var data = [], row;
for (var i = 0, ilen = res.MultipleTerritories.length; i < ilen; i++) {
row = [];
row[0] = res.MultipleTerritories[i].fname;
row[1] = res.MultipleTerritories[i].lname;
row[2] = res.MultipleTerritories[i].email;
row[3] = res.MultipleTerritories[i].suburb;
row[4] = res.MultipleTerritories[i].postcode;
row[5] = res.MultipleTerritories[i].revenue;
row[6] = res.MultipleTerritories[i].noitems;
row[7] = res.MultipleTerritories[i].typeitems;
data[res.MultipleTerritories[i].id - 1] = row;
}
$console.text('Data loaded');
handsontable.loadData(data);
}
});
}).click(); //execute immediately
});
</script>
</body>
</html>
从上面的脚本中调用以下脚本:
functions.php script:
function &getConnection(){
$db = new PDO('mysql:host=localhost;dbname=suburbma;charset=utf8', 'suburbma***', '*****');
function closeConnection ($db){
$db = NULL;
}
//create the database if does not exist
function createMultipleTerritoriesTable($db){
$db->exec("CREATE TABLE IF NOT EXISTS MultipleTerritories (id INTEGER PRIMARY KEY, fname TEXT, lname TEXT, email TEXT, suburb TEXT, postcode INTEGER, revenue INTEGER, noitems INTEGER, typeitems TEXT)");
}
function resetMultipleTerritoriesTable($db){
dropMultipleTerritoriesTable($db);
createMultipleTerritoriesTable($db);
loadDefaultMultipleTerritories($db);
}
function dropMultipleTerritoriesTable($db){
$db->exec("DROP TABLE IF EXISTS multiple_suburbs");
}
function loadDefaultMultipleTerritories($db){
$query = $db->prepare('INSERT INTO multiple_suburbs(id, fname, lname, email, suburb, postcode, revenue, noitems, typeitems) VALUES(:id, :fname, :lname, :email, :suburb, :postcode, :revenue, :noitems, :typeitems)');
$data = array(
array(
'id' => 1,
'fname' => '',
'lname' => '',
'email' => '',
'suburb' => '',
'postcode' => '',
'revenue' => '',
'noitems' => '',
'typitems' => ''
),
array(
'id' => 2,
'fname' => '',
'lname' => '',
'email' => '',
'suburb' => '',
'postcode' => '',
'revenue' => '',
'noitems' => '',
'typitems' => ''
),
array(
'id' => 3,
'fname' => '',
'lname' => '',
'email' => '',
'suburb' => '',
'postcode' => '',
'revenue' => '',
'noitems' => '',
'typitems' => ''
),
array(
'id' => 4,
'fname' => '',
'lname' => '',
'email' => '',
'suburb' => '',
'postcode' => '',
'revenue' => '',
'noitems' => '',
'typitems' => ''
),
array(
'id' => 5,
'fname' => '',
'lname' => '',
'email' => '',
'suburb' => '',
'postcode' => '',
'revenue' => '',
'noitems' => '',
'typitems' => ''
),
array(
'id' => 6,
'fname' => '',
'lname' => '',
'email' => '',
'suburb' => '',
'postcode' => '',
'revenue' => '',
'noitems' => '',
'typitems' => ''
),
array(
'id' => 7,
'fname' => '',
'lname' => '',
'email' => '',
'suburb' => '',
'postcode' => '',
'revenue' => '',
'noitems' => '',
'typitems' => ''
),
array(
'id' => 8,
'fname' => '',
'lname' => '',
'email' => '',
'suburb' => '',
'postcode' => '',
'revenue' => '',
'noitems' => '',
'typitems' => ''
)
);
foreach($data as $index => $value){
$query->bindValue(':id', $value['id'], PDO::PARAM_INT);
$query->bindValue(':fname', $value['fname'], PDO::PARAM_STR);
$query->bindValue(':lname', $value['lname'], PDO::PARAM_STR);
$query->bindValue(':email', $value['email'], PDO::PARAM_STR);
$query->bindValue(':suburb', $value['suburb'], PDO::PARAM_STR);
$query->bindValue(':postcode', $value['postcode'], PDO::PARAM_INT);
$query->bindValue(':revenue', $value['revenue'], PDO::PARAM_INT);
$query->bindValue(':noitems', $value['noitems'], PDO::PARAM_INT);
$query->bindValue(':typeitems', $value['typeitems'], PDO::PARAM_STR);
$query->execute();
}
}
function &loadMultipleTerritories($db){
$select = $db->prepare('SELECT * FROM multiple_suburbs ORDER BY id ASC LIMIT 100');
$select->execute();
return $select;
}
function multiple_suburbsTableExists($db){
$result = $db->query("SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='multiple_suburbs'");
$row = $result->fetch(PDO::FETCH_NUM);
return $row[0] > 0;
}
save.php:
<?php
require_once('functions.php');
try {
//open the database
$db = getConnection();
createMultipleTerritoriesTable($db);
$colMap = array(
0 => 'fname',
1 => 'lname',
2 => 'email',
3 => 'suburb',
4 => 'postocde',
5 => 'revenue',
6 => 'noitems',
7 => 'typeitems'
);
if (isset($_POST['changes']) && $_POST['changes']) {
foreach ($_POST['changes'] as $change) {
$rowId = $change[0] + 1;
$colId = $change[1];
$newVal = $change[8];
if (!isset($colMap[$colId])) {
echo "\n spadam";
continue;
}
$select = $db->prepare('SELECT id FROM multiple_suburbs WHERE id=? LIMIT 1');
$select->execute(array(
$rowId
));
if ($row = $select->fetch()) {
$query = $db->prepare('UPDATE multiple_suburbs SET `' . $colMap[$colId] . '` = :newVal WHERE id = :id');
} else {
$query = $db->prepare('INSERT INTO multiple_suburbs (id, `' . $colMap[$colId] . '`) VALUES(:id, :newVal)');
}
$query->bindValue(':id', $rowId, PDO::PARAM_INT);
$query->bindValue(':newVal', $newVal, PDO::PARAM_STR);
$query->execute();
}
} elseif (isset($_POST['data']) && $_POST['data']) {
$select = $db->prepare('DELETE FROM multiple_suburbs');
$select->execute();
for ($r = 0, $rlen = count($_POST['data']); $r < $rlen; $r++) {
$rowId = $r + 1;
for ($c = 0, $clen = count($_POST['data'][$r]); $c < $clen; $c++) {
if (!isset($colMap[$c])) {
continue;
}
$newVal = $_POST['data'][$r][$c];
$select = $db->prepare('SELECT id FROM multiple_suburbs WHERE id=? LIMIT 1');
$select->execute(array(
$rowId
));
if ($row = $select->fetch()) {
$query = $db->prepare('UPDATE multiple_suburbs SET `' . $colMap[$c] . '` = :newVal WHERE id = :id');
} else {
$query = $db->prepare('INSERT INTO multiple_suburbs (id, `' . $colMap[$c] . '`) VALUES(:id, :newVal)');
}
$query->bindValue(':id', $rowId, PDO::PARAM_INT);
$query->bindValue(':newVal', $newVal, PDO::PARAM_STR);
$query->execute();
}
}
}
$out = array(
'result' => 'ok'
);
echo json_encode($out);
closeConnection($db);
}
catch (PDOException $e) {
print 'Exception : ' . $e->getMessage();
}
?>
reset.php:
<?php
require_once('functions.php');
try {
$db = getConnection();
resetMultipleTerritoriesTable($db);
closeConnection($db);
}
catch (PDOException $e) {
print 'Exception : ' . $e->getMessage();
}
load.php:
<?php
/**
* This is an example code that shows how you can load Handsontable data from server using PHP with PDO (SQLite).
* This code is not intended to be maximally efficient nor safe. It is for demonstrational purposes only.
* Changes and more examples in different languages are welcome.
*
* Copyright 2012, Marcin Warpechowski
* Licensed under the MIT license.
* http://github.com/handsontable/handsontable/
*/
require_once('functions.php');
try {
//open the database
$db = getConnection();
if(!multiple_suburbsTableExists($db)){
resetMultipleTerritoriesTable($db);
}
//select all data from the table
$result = loadMultipleTerritories($db);
$out = array(
'multiple_suburbs' => $result->fetchAll(PDO::FETCH_ASSOC)
);
echo json_encode($out);
// close the database connection
closeConnection($db);
}
catch (PDOException $e) {
print 'Exception : ' . $e->getMessage();
}
?>