PHPを使用してMysqlの単一列にJSONデータを挿入したい
<input type="text" name="text1" />
<input type="text" name="text2" />
$jsondata = '[{"value1":{ "text":"text1", "text2":"text2"},"value1":{ "text":"text1", "text2":"text2"}}]';
INSERT INTO tablename (row) VALUES ($jsondata);
それが可能だ
または、JSONファイルを生成してからインポートすることもできます。
ありがとうございました
1PHPでJSONファイルを読み取ります。
PHP supports the function file_get_contents() which will read the entire file and returns it as a string.
//read the json file contents
$jsondata = file_get_contents('yourjsonfilename.json');
2 JSON文字列をPHP配列に変換します。
//convert json object to php associative array
$data = json_decode($jsondata, true);
The first parameter $jsondata contains the JSON file contents. The second parameter true will convert the string into PHP associative array.
3 PHP配列値を解析し、変数に格納します。
//get the details
$id = $data['Id'];
$name = $data['personal']['name'];
$age = $data['personal']['age'];
$streetaddress = $data['personal']['address']['streetaddress'];
$city = $data['personal']['address']['city'];
$state = $data['personal']['address']['state'];
$postalcode = $data['personal']['address']['postalcode'];
4 PHPコードを使用してMySQLデータベースにJSONを挿入する次に、以下のクエリを使用して、抽出されたJSONオブジェクト値をMySQLテーブルに挿入します。
//insert into mysql table
$sql = "INSERT INTO tbl_students(studentId, name, age, streetaddress, city, state, postalcode)
VALUES('$id', '$name', '$age', '$streetaddress', '$city', '$state', '$postalcode')";
if(!mysqli_query($con, $sql))
{
die('Error : ' . mysql_error());
}
これで、次のようにJSONデータがMySQLデータベースに正常にインポートされました。
{
"Id": "ST001",
"personal": {
"name": "John Smith",
"age": "29",
"address": {
"streetaddress": "5 14th Street",
"city": "New York",
"state": "NY",
"postalcode": "12548"
}
}
}
<?php
$josndata = '{
"student":{ "name":"Harry", "country":"United State", "ContactNo":2545454 }
}';
// Database connection
$conn = new mysqli('localhost', 'username', 'password', 'databasename');
// Insert data Query
$sql = "INSERT INTO student_table ( name, jsondata )
VALUES ('Harry', '$josndata')";
if ($conn->query($sql) === TRUE) {
echo "Insert your JSON record successfully";
}
?>
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加