Insert data from an array into a mysql database

1

I get a json from an android application. This json is a java class that was converted with json's Gson to a string. After the web server in php receives this json I convert to an array.

I want to make a generic insert in my web server, where it automatically scrolls through the array and inserts in the table passed by parameter.

ex:

public function create($array){

    /*
     * O nome da tabela é recebida por um post e é passada por um construtor
     * $condição: Aqui eu teria que pegar os nomes das keys e deixar assim por exempo: nome, idade, sexo
     * $valores: tenho que pegar o conteudo dos arrays. Ai tenho que verificar se é uma string ou data ou float para deixar entre aspas.Ex: 'rafael', 18, '1987-12-12'
    */
    $query = "INSERT INTO $this->tabela ( $condicao ) VALUES ( $valores )";

    $flag = mysqli_query($this->con, $query);

    if($flag === TRUE){
        $json['flag'] = TRUE;
    } else {
        $json['flag'] = FALSE;
    }

    mysqli_close($this->con);
    return $json;

}

I do not know if there is an easier way to do this than I want, or if there is any api ready.

All help is welcome!

    
asked by anonymous 07.01.2017 / 14:16

2 answers

1

You can use code like this, it's a template for you to have a base

$campos      = implode(', ', array_keys($array));
$valores     = '"'.implode('", "', $array).'"'; 
$query       = "INSERT INTO $this->tabela 
                              ( $campos ) 
                       VALUES ( $valores )"; 
    
07.01.2017 / 21:42
0

A suggestion to solve your problem. You said that you need to retrieve the values of a JSON and that you want to make them into an array.

There is a function in PHP that retrieves data from a JSON and transforms it into objects.

Here's an example

$obj = json_decode($json_recebido);

echo "nome: " . $obj->$nome . " idade: " $obj->$idade . " sexo: " . $obj->sexo;
    
07.01.2017 / 15:59