Assign a name to a $ row?

0

I have this function:

printf ("%s (%s)\n", $row["id"], $row["name"]);

Which shows the data of X user whose value is in the respective tables, id and name.

But only shows the data and now, what I want to do is assign a name to each data.

For example:

ID: Display the user ID (id) Name: Displays the name of the user (name)

<!DOCTYPE html>
<html>
<body>

<?php
$enlace = mysqli_connect("host", "user", "pw", "db");

/* verificar la conexión */
if (mysqli_connect_errno()) {
    printf("Conexión fallida: %s\n", mysqli_connect_error());
    exit();
}
$nick = urlencode($_GET['nick']);
$consulta = "SELECT id, name FROM player WHERE name='".$nick."'";

if ($resultado = mysqli_query($enlace, $consulta)) {

    /* obtener array asociativo */
    while ($row = mysqli_fetch_assoc($resultado)) {
        printf ("%s (%s)\n", $row["id"], $row["name"]);
    }

    /* liberar el conjunto de resultados */
    mysqli_free_result($resultado);
}

/* cerrar la conexión */
mysqli_close($link);
?>

</body>
</html>

I have that code, but when I run it, it automatically shows me the value of the user with respect to each table (id, name). And I do not want that, I want you to say.

ID: user id (in this case, the value assigned in id.

Name: user name (the name assigned in name

    
asked by Py. Yuir 01.02.2017 в 01:48
source

2 answers

0

I do not know if what you want to do is something like this:

    /* obtener array asociativo */

while ($row = mysqli_fetch_assoc($resultado)) {

    $id   = $row["id"];
    $name = $row["name"];
    printf ("%s (%s)\n", "ID: " + $id, " Nombre: " + $name]);
}

or you want to create variables dynamically to use them outside the loop, in this case look at this thread: How to dynamically create variables within a while?

    
answered by 01.02.2017 / 11:56
source
0

I understand that what you want is to return the name of the column plus the value.

This you have to specify in the while, for example:

/* obtener array asociativo */
    while ($row = mysqli_fetch_assoc($resultado)) {
        echo "ID: " . $row["id"] . "<br>";
        echo "Nombre: " . $row["name"] . "<br>";

    }

With this you define at the beginning of the value what each field refers to.

Finally I see that your code is vulnerable to sql injection. I leave the following link where it explains how to avoid it: How to avoid SQL injection in PHP?

    
answered by 01.02.2017 в 11:00