将PHP变量分配给每一行

时间:2014-03-03 21:30:53

标签: php mysql

以下mysql查询从'住宅'表中获取最后4条记录,但我正在尝试为每一行(特别是第3 [3]列)分配一个php变量($ postcode)以供使用另一页。以下似乎没有正确地将行拆分为每个变量?

<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$result = mysqli_query($con,"SELECT * FROM residential ORDER BY My_id DESC LIMIT 4");

$postcodes = array();

while ($row = mysqli_fetch_array($result))  
{
$postcodes[] = $row[3];
}

echo "location one " . $postcodes[0];
echo "<br>";
echo "location two " . $postcodes[1];
echo "<br>";
echo "location three " . $postcodes[2];

mysqli_close($con);
?>

1 个答案:

答案 0 :(得分:2)

fetch调用获取单个ROW数据。你只是一遍又一遍地分配每行的第3列。

你可能想要:

$postcodes = array();
while ($row = ...) {
    $postcodes[] = $row[3];
}
var_dump($postcodes);