m3tsys
m3tsys

Reputation: 3969

How to import javascript style code to phpmyadmin?

How can i import data like this separated by , to a mysql database?

data = [{
    "q": "some text",
    "a": "var1",
    "b": "var2",
    "c": "var3",
    "p": "1.jpg",
    "v": "a",
    "id": 1
}, {
    "q": "another question",
    "a": "var 2.1",
    "b": "var 2.1",
    "c": "var 2.1",
    "v": "a",
    "id": 2
}

The mysql database table is structured as the data with the columns: id / q / a / b / c / p / v

I've tried to import the data directly but it doesn't work?

Any advices?

Upvotes: 0

Views: 607

Answers (1)

Spoke44
Spoke44

Reputation: 988

In PHP/PDO it's just for a one shot insertion :

$json = '[{
    "q": "some text",
    "a": "var1",
    "b": "var2",
    "c": "var3",
    "p": "1.jpg",
    "v": "a",
    "id": 1
}, {
    "q": "another question",
    "a": "var 2.1",
    "b": "var 2.1",
    "c": "var 2.1",
    "v": "a",
    "id": 2
}]';

$datas = json_decode($json, true); // transform json to php array

$db = connect(); // you have to change this with your PDO connection

$dataset = array("q", "a","b", "c", "p", "v", "id");
foreach($datas as &$data){
  foreach($dataset as $elem){
     if(!isset($data[$elem]))
        $data[$elem] = "";
  }
  $req = $db->prepare("INSERT INTO table (q, a, b, c, p, v, id) VALUES (:q, :a, :b, :c, :p, :v, :id)");
  $req->execute($data);
}

Considere to lock the table before insertions and unlock after if there are a lot of rows.

Upvotes: 1

Related Questions