【发布时间】:2018-09-23 14:10:09
【问题描述】:
这就是我将静态数据插入数据库表的方式:
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
// set the PDO error mode to exception
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
$campaign = (isset($_POST['campaign'])) ? $_POST['campaign'] : null;
$salutation = $_POST['salutation'];
$firstname = $_POST['first_name'];
$lastname = $_POST['surname'];
$address = $_POST['address'];
$zipcode = $_POST['zipcode'];
$location = $_POST['location'];
$country = $_POST['country'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$date_of_birth = (isset($_POST['day']) && is_numeric($_POST['day']) && isset($_POST['month']) && $_POST['month'] != 'Monat' && isset($_POST['year']) && is_numeric($_POST['year'])) ? $_POST['day'] . '.' . $_POST['month'] . '.' . $_POST['year'] : '';
$ip = $_SERVER['REMOTE_ADDR'];
$created_on = time();
$stmt = $conn->prepare ("INSERT INTO t_weltwoche_address_infos2018_test (salutation, firstname, lastname, address, loctation, country, phone, email, date_of_birth, remoteAddress, createdon) VALUES (:salutation, :firstname, :lastname, :address, :loctation, :country, :phone, :email, :date_of_birth, :remoteAddress, :createdon)");
$stmt -> bindParam(':salutation', $salutation);
$stmt -> bindParam(':firstname', $firstname);
$stmt -> bindParam(':surname', $lastname);
$stmt -> bindParam(':address', $address);
$stmt -> bindParam(':loctation', $location);
$stmt -> bindParam(':country', $country);
$stmt -> bindParam(':phone', $phone);
$stmt -> bindParam(':email', $email);
$stmt -> bindParam(':date_of_birth', $date_of_birth);
$stmt -> bindParam(':remoteAddress', $ip);
$stmt -> bindParam(':createdon', $created_on);
$stmt -> execute();
}
catch(PDOException $e) {
$conn = null;
echo $e;
}
这只是一个测试,它似乎有效。现在我想动态地做所有事情。
$json = json_decode(file_get_contents('/srv/www/micro/weltwochen.lasttry.db.json'));
使用 $json 我得到一个 JSON 对象。我对 JSON 文件的值不感兴趣,但我想将它的属性用于我的 MySQL 表的列。
所有 JSON 属性的调用方式与 $_POST[] 的字符串相同。
示例
如果 JSON 有一个名为 first_name 的属性,则插入 $_POST['first_name'] 的值。
我该怎么做?
【问题讨论】:
-
JSON数据文件的格式是什么?