I would like to import data from a JSON file to a database table. I'm using Doctrine with the pdo_sqlite driver and the following entity is configured :
/**
* @Entity @Table(name="mytable")
**/
class MyClass
{
/** @Id @Column(type="integer") @GeneratedValue *
* @Column(type="integer")
*/
var $id;
/** @Column(type="string") **/
var $name;
/** @Column(type="simple_array") **/
var $parameters;
function __construct($name, $parameters)
{
$this->name = $name;
$this->parameters = $parameters;
}
// getters and setters here
}
I have created a simple import method :
function importFromJson($tableName, $fileName)
{
if (file_exists($fileName)) {
$data = json_decode(file_get_contents($fileName));
if (is_array($data)) {
$connection = getEm()->getConnection();
foreach($data as $tuple) {
if (is_object($tuple)) {
$connection->insert($tableName, (array)$tuple);
}
}
}
}
}
My import.json file contains the following text :
[
{
"name": "A name",
"parameters": ["a","b","c"]
}
]
When I call my import method :
importFromJson("mytable", "import.json");
I get the following error :
An exception occurred while executing 'INSERT INTO mytable (name, parameters) VALUES (?, ?)' with params ["A name", ["a","b","c"]]:
Array to string conversion C:\myproject\vendor\doctrine\dbal\lib\Doctrine\DBAL\DBALException.php:119 C:\myproject\vendor\doctrine\dbal\lib\Doctrine\DBAL\Connection.php:996 C:\myproject\vendor\doctrine\dbal\lib\Doctrine\DBAL\Connection.php:696 C:\myproject\lib\import.php:39
Isn't the exact purpose of the simple_array type to convert arrays to strings that can be stored in the database ?
json_encode($array)
function. This will convert your array to string. Then while retrieving data, calljson_decode($string)
function. – Tomas Votruba