How to write data from a form into a database by converting the fields to JSON?

3

I have some form, example:

<form action="confi.php" method="post" enctype="multipart/form-data">
   <p><input type="text" name="nome" value="nome">
   <p><input type="text" name="email" value="email">
   <p><button type="submit">Submit</button>
</form>

I would like to write these fields (like a JSON) to a table.

confi.php

//minha conexão com o banco

$sql = "INSERT INTO 'banco'.'tabela'('json') VALUES ('$json')";

My question is, how do I get and convert the fields / values filled in the form into a JSON file to write to the table in this way?

@UPDATE

IwasabletomountJSONwithjson_encodeassuggested.

Butwhentheregistryarrivesinthedatabase,thevalueis"Array".

$myArr = array("nome" => $_POST['nome']
        , "email" => $_POST['email']);
json_encode($myArr);

Insert into the bank

$sql = "INSERT INTO 'tabela'('json') VALUES ('$myArr');";

Table

How do I enter the actual json value?

    
asked by anonymous 15.03.2017 / 16:19

2 answers

1

Only use the json_encode($_POST) function

json_enconde function documentation

Remembering that according to the documentation, the jason_encode() function does not change the array you pass to it, it only returns the string JSON. That is:

$myArr = array("Um" => 1, "Dois" => 2, "Três" => 3);
$json = json_encode($myArr);

But if you want to save data to JSON , as commented in your question, it might be best to use MongoDB or other databases NoSQL

    
15.03.2017 / 17:44
3

Although answered, I'll 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 standard data format.

Then storing data like JSON in MySQL would go against the intent of a relational database manager system (though some call the NoSQL database "non-normalized relational", which to me does not sound right) . However, MySQL has supported JSON since version 5, as well as PostgreSQL (which, in this respect at least, has more functions). And the SQL Server 2014+ also, which I expected a lot .

Although you were better off using MongoDB, CouchDB, Cassandra, MarkLogic, others, you can still store the JSON data as a string in the standard 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 PDO template (ie, always use MySQLi ).

    
15.03.2017 / 19:06