我正在使用 Gridstack 库创建仪表板。小部件 x、y、宽度和高度可以放入 json 中,我正在尝试将此 json 保存到 MySQL 中。
当我在大学时,我通过按一个按钮来工作,获得了 json 数组以进入 MySQL 中的表。当我回家时,它停止工作了。我正在使用 PHP 和 MySQL。
第一个问题是下面的行停止工作(在我回家之前就很好,没有碰代码)。
$data = $_GET['name'];
必须更改为:
$data = isset($_GET['name']);
不知道为什么。 PHP 的其余部分也停止工作。没有错误,只是什么都不做。这不是我的脚本有问题。所有 Javascript 都工作得很好。
其余代码:
$('#save').click(function(){
var res = _.map($('.grid-stack .grid-stack-item:visible'), function (el) {
el = $(el);
var node = el.data('_gridstack_node');
return {
id: el.attr('data-custom-id'),
x: node.x,
y: node.y,
width: node.width,
height: node.height
};
window.location.href = "index.php?string=" + JSON.stringify(res);
});
<?php
$connect = mysqli_connect("localhost", "root", "", "widgetCollection");
$data = isset($_GET['string']);
//$data = $_POST['variable'];
$array = json_decode($data, true);
foreach((array)$array as $row) {
$sql = "INSERT INTO grids(x, y, width, height) VALUES('".$row["x"]."', '".$row["y"]."', '".$row["width"]."', '".$row["height"]."');";
mysqli_query($connect, $sql);
}
?>
alert(JSON.stringify(res));
});
最佳答案
Isset 允许您测试数组中某个键是否存在,并将返回一个 bool 值。
你不应该那样使用isset。
你可以这样写:
if (isset($_GET['name'])) {
$data = $_GET['name'] ;
}
这将测试数组 $_GET 中键“name”是否存在,如果找到,将进入“if”条件并设置变量。
关于php - json 到 mysql 停止工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42737495/