Paulo Soares Paulo Soares - 3 months ago 8
MySQL Question

Turn PHP MySQL query output into variable

I have a problem that is giving me a headache. I'm fairly new to PHP and MySQL interacting, and coding in general (about 3 months since I first dived into it), so I'm still learning the ropes, so to speak.

The thing is, I have a page that receives data through $_POST from another. All is fine for well. The page receives the data, which is an ID number, and echoes the item's characteristics available in the database corresponding to that ID.

This part of the code works just fine.

$sql = "SELECT nome, preco, `status` FROM produtos WHERE id = $_POST[id]";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
echo "Nome: "."<span style='color: red;'>".$row["nome"].
"</span>".
"<br>"."Preço: "."<span style='color: red;'>".
"R$".$row["preco"]."</span>"."<br><br>".$row["status"];
}
}


What I want, is to turn the values echoed into variables, so that I can set them as default value in another form and send that one to another page. Apparently, $row['nome'], for example, isn't available for re-use outside of the instance above.

<form method="post" action="?p=venda">
<input type="text" name="nome" value="<?php echo $row["nome"]; ?>">
<input type="text" name="preco" value="<?php echo $row["preco"]; ?>">

<input type="submit" name="change" value="Efetuar">
</form>


I know this code is prone to SQL injection, but I'm not looking into it right now. This will be a sort of offline program to help me with organizing some of my stuff, so, for now, I don't have to worry about security (not that I'll keep ignoring these issues).

Thanks in advance.

Answer

Assign $row to a variable and treat it as an array() outside the while loop.

$sql = "SELECT nome, preco, `status` FROM produtos WHERE id = $_POST[id]";
$result =  mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0){
    while($row = mysqli_fetch_assoc($result)){
        $array = $row; // assign $row a variable.

        echo "Nome: "."<span style='color: red;'>".$row["nome"].
        "</span>".
        "<br>"."Preço: "."<span style='color: red;'>".
        "R$".$row["preco"]."</span>"."<br><br>".$row["status"]; 
    }
}

// example
echo($array['nome']);
Comments