将表的每一行关联到不同的变量

时间:2018-07-08 13:31:33

标签: php

实际上,我用代码将所有结果一起打印出来,但目标是将每一行与一个变量关联。

$sql = "SELECT modello FROM THING;";

$result = $conn->query($sql);

if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
    echo $row["modello"];   //this print all result but want to associate first result to variable $first and second to $second
}
} else {
echo "0 results";
}

2 个答案:

答案 0 :(得分:0)

echo $row["modello"];更改为$modellos[] = $row["modello"];,如下例所示:

$result = $conn->query("SELECT modello FROM THING");
$modellos = [];
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $modellos[] = $row["modello"];
    }
} else {
    echo "0 results";
}

现在$modellos$modellos[0]中具有第一个,在$modellos[1]中具有第二个,而在$modellos[2]中具有第三个,依此类推,而在while循环之后。如果您确实在$first$second中需要它们,请在循环后添加:

$first = $modellos[0];
$second = $modellos[1];

答案 1 :(得分:0)

您可以使用数组存储结果。

$i = 0;
while($row = $result->fetch_assoc()) {
    ${"result" . $i} = $row["modello"];
    $i++;
}

但是,如果您确实需要将每一行与一个变量相关联,则可以使用:

:hover
相关问题