Although answered, I will add this to the discussion:
JSON (Javascript Object Notation, because it has the format of a JS object) is not a file format, first. Yes, an open data standard format.
Later, storing data as JSON in Mysql would go against the intention of a relational database manager system (although, some call the Nosql databases "non-standard relational", which to me doesn’t sound good). Even so, the Mysql has support for JSON since version 5, as well as Postgresql (which, in this regard at least, has more functions). And SQL Server 2014+ also, what I’ve waited for so long.
Although you were better using Mongodb, Couchdb, Cassandra, Marklogic, others, you can still store the JSON data as string in the normalized relational database.
A simple code to store the $_POST in the database as JSON is as follows:
try {
// Conexão com o banco de dados e seus atributos
$conexao = new \PDO("mysql:host=localhost;dbname=banco_de_dados", 'usuario', 'senha');
$conexao->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
// Query com o placeholder :json
$query = 'INSERT INTO tabela (json) VALUES (:json)';
// Usando prepared statements, porque é mais seguro e melhora a performance
$insert = $conexao->prepare($query);
// Diz pro MySQL que o parametro representado pelo placeholder :json na query é uma string, convertendo $_POST em uma string JSON
$insert->bindParam(':json', json_encode($_POST, JSON_NUMERIC_CHECK), PDO::PARAM_STR);
// Executa a query
$insert->execute();
// Verifica se a inclusão foi feita
$linhas_afetadas = $insert->rowCount();
// XXX Aqui você pode mudar o número de acordo com o número de linhas que voc~es espera serem afetadas
if($linhas_afetadas == 1) {
echo json_encode(array('message' => 'Dados inseridos com sucesso'));
}
} catch (PDOException $ex) {
echo json_encode(array('message' => $ex->getMessage);
}
The code has not been tested, but can be easily used, since it uses a well-known model with PDO (is, always use PDO or Mysqli).
Although you may prefer to use your database, you can try Mongodb, a JSON database that does not use SQL. If you want to save the data in JSON as shown in the example,
nome:value e-mail:value
, it is better to use Mongodb. See here: http://www.itexto.net/devkico/? p=706– Gabriel C.
Thanks for the tip, I will give a study in Mongodb, but at the moment I can not change it because it involves other applications
– Bruno Alves
json_encode()
returns the JSON string! Then it would look$myArr = json_encode($myArr);
. It’s good to remember that this is a very common standard in PHP: functions do not change the argument you give them!– Daniel