如何在变量中存储单个选定的行值?

时间:2015-04-19 14:38:33

标签: php mysql sql mysqli

在“汽车”行中输入“BMW x1”

  $sql = "SELECT cars FROM table LIMIT 1";

        $result = $con->query($sql);
        if ($result->num_rows > 0) {
            $rows[] = $result->fetch_row();
            $result->free();
        }
echo json_encode($rows[0]);

输出:["BMWx1"]

到目前为止一切顺利。现在我如何让我的变量$ cars等于“BMW x1”

e.g:

  echo $cars; 
  output: BMWx1

谢谢你

1 个答案:

答案 0 :(得分:1)

如果您只是阅读一行,请不要将该行推到数组上。 fetch_assoc返回一个关联数组,其中包含从查询中检索到的行(如果没有选择任何内容,则返回false)。只需使用它并访问所需的列。

$result = $con->query($sql);
$row = $result->fetch_assoc();
if ($row) {
    $cars = $row['cars'];
}
相关问题