Create a JSON from a MySQL query?

0
function connectDB(){

   $conexion = mysqli_connect("servidor", "usuario", "contraseña", "base de datos");
    if($conexion){
        echo 'La conexión de la base de datos se ha hecho satisfactoriamente
';
    }else{
        echo 'Ha sucedido un error inesperado en la conexión de la base de datos
';
    }   
    return $conexion;
}

It is my base code to make the connection to the database.

Although, I do not know exactly how to do to select the table from where the data will be obtained.

I have this one that I used in a separate project, but I do not know if it is valid for what I want to do, since I still do not understand very well how to do it, therefore I have not done tests:

$nick = urlencode($_GET['nick']);
mysql_select_db("statistiques", $link);
$result = mysql_query("SELECT * FROM player WHERE name='".$nick."'", $link);

What I want to do is summarized more or less in these tutorials:

Creating a JSON from of a query in MySQL.

Manage JSON in PHP.

But I still do not know how to do all that and I do not understand the tutorial very well.

Within the table statistiques , there is another call player . Whose data I want to set so that others can do queries from my file are :

id, name, title, experience, first, bootcamp, round_played, shaman_cheese, saved_mice, saved_mice_hard, saved_mice_divine, cheese_gathered .

    
asked by Py. Yuir 01.02.2017 в 20:38
source

1 answer

2

I will answer the question in the title using the query that you leave as an example because in the post I did not understand you correctly.

This is the query of your post updated to MySQLi and filtering the nick to avoid SQL injections that destroy your database:

$nick = mysqli_real_escape_string($link, $_GET['nick']);
mysqli_select_db($link, 'statistiques');
$result = mysqli_query($link, "SELECT * FROM player WHERE name = '{$nick}'");

To export the data from this query to JSON, the first thing we have to do is pass the data back to an array:

while($row = mysqli_fetch_array($result)) $array[] = $row;

And the next step is to use the json_encode () function to convert that array to JSON:

$json = json_encode($array);

With these two steps you already have the JSON saved in the variable $ json in the form of a string.

    
answered by 01.02.2017 / 21:38
source