-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathJSONtoSQL_PHP.php
More file actions
40 lines (29 loc) · 863 Bytes
/
JSONtoSQL_PHP.php
File metadata and controls
40 lines (29 loc) · 863 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<?php
// READ JSON
$cd = dirname(__FILE__);
$jsonString = file_get_contents($cd."/CLData.json");
$data = json_decode($jsonString, true);
try {
// Open DB connection
$dbh = new PDO("sqlite:".$cd."/CLData.db");
// Append to DB
$fields = array_keys((array)$data[0]);
$qmarks = array_fill(0, count($data[0]), '?');
$dbh->query("DELETE FROM cldata;");
$sql = "INSERT INTO cldata (" . implode(",", $fields) . ")";
$sql = $sql . " VALUES (" . implode(",", $qmarks) . ")";
$dbh->beginTransaction();
foreach($data as $d) {
$stmt = $dbh->prepare($sql);
$stmt->execute(array_values((array)$d));
}
$dbh->commit();
}
catch(PDOException $e) {
echo $e->getMessage()."\n";
exit;
}
// Close DB connection
$dbh = null;
echo "Successfully migrated JSON data to SQL database! \n";
?>