PHP mysqli空数组

时间:2015-01-13 19:14:46

标签: php arrays mysqli

我对我的代码有疑问。当我尝试用我的获取数组填充我的html时,我只得到空格而不是实际结果。谁能告诉我为什么?

<?php
require_once("php/loader.inc.php");
include("php/header.php");
include("php/userpanel.php");
$gebruiker = $_SESSION['user'];
?>


<div class="large-8 columns">
<div class="row">  


<?php
$query = "
SELECT
   items.naam,
   items.prijs,
   items.image_url
FROM inventory
JOIN items
 ON items.id = inventory.item_id
WHERE
 gebruiker_id = ?
";

$stmt = $db->prepare($query);
$stmt-> bind_param('i', $gebruiker->id);

$stmt->execute();

$result = $stmt->get_result();
while ($row = $result->fetch_assoc())
{
    $user_items[] = $row;

   echo '<div class="large-3 small-4 columns">
<img src="'. $user_items['image_url'] .'">
<div class="panel">
    <h6>'. $user_items['naam'] .'</h6>
<h6 class="subheader">'. $user_items['prijs'] .'</h6>
</div>
</div>'; 

}
?>

顺便说一下,当我尝试print_r($user_items);时,它会给我预期的结果。

提前致谢!

2 个答案:

答案 0 :(得分:2)

我想你想改变这个:

$user_items[] = $row;

到此:

$user_items = $row;

否则您的索引是1维'更深'

举个例子:

$row = array("image_url" => "xy");

这一行之后:

$user_items[] = $row;

您无法通过以下方式访问它:

echo $user_items["image_url"];  //Wrong

你必须这样做:

echo $user_items[0]["image_url"];  //works

答案 1 :(得分:1)

您不需要此行$user_items[] = $row;,您可以直接使用$row

while ($row = $result->fetch_assoc())
{        
   echo '<div class="large-3 small-4 columns">
  <img src="'. $row['image_url'] .'">
  <div class="panel">
    <h6>'. $row['naam'] .'</h6>
    <h6 class="subheader">'. $row['prijs'] .'</h6>
  </div>
  </div>';     
}