根据另一个表的结果导入mysql

qxsslcnc  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(291)

我希望将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');

因此,基于这种Map(即,street address是字段11),我希望能够解析发布的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;

}

以下是示例json:

{
"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); 我期待的地方 REPLACE INTO fields_testloan (streetaddress, city) VALUES ('123 HOPE STREET','Philadelphia'); 这有可能吗?

fslejnso

fslejnso1#

在阅读 fields 表中,创建从字段IDMap到变量名的关联数组。

$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)";

相关问题