我希望将JSON数据导入到表中,但我只想根据另一个表中的内容来获取字段。
这是我的示例数据库:
Array: [a, b, c]
因此,然后基于该映射(即街道地址为字段11),我希望能够解析POSTed JSON并获取这些字段并将其插入到另一个表中。
CREATE TABLE `fields` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`fieldname` varchar(50) DEFAULT NULL,
`encompassid` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
INSERT INTO `fields` (`id`, `fieldname`, `fileid`)
VALUES
(1,'streetaddress','11'),
(2,'city','12');
当前我的代码返回正确的查询,除了变量没有来自JSON的数据,它们只是一个字符串。
CREATE TABLE `testfile` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`streetname` varchar(100) DEFAULT NULL,
`city` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=29 DEFAULT CHARSET=utf8mb4;
这是示例JSON:
$con=mysqli_connect($dbhost,$dbuser,$dbpassword,$db);
$result = mysqli_query($con,"SELECT * FROM fields");
while($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
$items = array();
$itemsV = array();
$sfv = '';
foreach ($data as $obj1) {
if($sfv != "\$".$obj1['fieldname']." = \$obj2->{'".$obj1['fileid']."'};"){
$sfv .= "\$".$obj1['fieldname']." = \$obj2->{'".$obj1['fileid']."'};";
}
$items[] .= $obj1['fieldname'];
$itemsV[] .= "\$".$obj1['fieldname'];
}
}
$string = file_get_contents('php://input');
$data2 = json_decode($string);
foreach ($data2 as $obj2) {
$values = implode(',', $itemsV);
eval("\$sfv;");
$columns = implode(", ",$items);
$insert = "REPLACE INTO testfile ($columns) VALUES ($values);";
echo $insert;
}
当前输出看起来像这样:{
"serializedExport": null,
"format": 1,
"fields": {
"2": "100000",
"3": "4.500",
"4": "360",
"5": "760.03",
"6": "",
"8": "",
"9": "",
"10": "",
"11": "123 HOPE STREET",
"12": "Philadelphia",
"13": "",
"14": "PA",
"15": "19119",
"16": "1",
"17": ""
}
}
我在哪里REPLACE INTO fields_testloan (streetaddress, city) VALUES ($streetaddress,$city);
这可能吗?
答案 0 :(得分:2)
在读取fields
表时,创建一个从字段ID映射到变量名的关联数组。
$fields = array();
while ($row = mysqli_fetch_assoc($result)) {
$fields[$row['fileid']] = $row['fieldname'];
}
然后在处理JSON时,创建字段名称和值的数组。使用json_decode()
的第二个参数,可以得到一个关联数组而不是对象,因此可以使用foreach
对其进行循环。
$string = file_get_contenst("php://input");
$data2 = json_decode($string, true);
$colnames = array();
$colvalues = array();
foreach ($data["fields"] as $fieldid => $fieldvalue) {
if (isset($fields[$fieldid])) {
$colnames[] = $fields[$fieldid];
$colvalues[] = "'" . mysqli_real_escape_string($con, $fieldvalue) . "'";
}
}
$cols_string = implode(",", $colnames);
$vals_string = implode(",", $colvalues);
$sql = "REPLACE INTO testfile ($cols_string) VALUES ($vals_string)";