我已经用问题注释了我的代码,有关解决此问题的任何建议?现在被卡在上面了几个小时。

<?php
include("header.php");
$inv = mysql_query("SELECT `item_id` FROM `user_items` WHERE `user_id`='".$_SESSION['uid']."'") or die(mysql_error());
$linv = mysql_fetch_array($inv);

//Need to display all item_id's from the user_items table where the user_id field = $_SESSION['uid'] (or 1 for testing purposes.)
//For some reason, every foreach and while loop method i have tried is giing me false data (1,1).  The right data should be: 1, 4.
//The database table contains 3 columns: slot_id, user_id, item_id.
//Those columns contain the following data: 1       1          1
//                                          2       2          4
//                                          3       1          4
//surely this should return $linv as an array containing the values 1 and 4?  What's going on?


}
include("footer.php");
?>

最佳答案

更改



$linv = mysql_fetch_array($inv);
while(list($key, $value) = each($linv))
{
    echo($value);
}









while($linv = mysql_fetch_array($inv))
{
    echo $linv['item_id'] . ' ';
}





编辑:问题原因
-第一个问题是$linv = mysql_fetch_array仅返回下一行并将其作为数组存储在$linv中,从一开始它就从第0行开始
所以第一个问题是您丢失了一个检索所有行的循环
-现在您可能会问自己:“如果我只得到一行,为什么输出为1 1”,这是因为mysql_fetch_array接受了第二个参数,该参数不利于获取模式(对于只能访问的关联数组,MYSQL_ASSOC带有查询中的列名的MYSQL_NUMERIC(仅可使用数字0、1,2 ...访问的数字数组,以相同顺序在select子句中指定列),当您不传递该参数时,则使用MYSQL_BOTH将默认使用,您将获得第一行,例如[“ 0” =>“ 1”,“ item_id” =>“ 1”]
您正在做的只是循环浏览第一行中的所有元素

关于php - 使用php无法显示数据库结果,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30560340/

10-12 00:14
查看更多