简体   繁体   中英

Having trouble displaying results from a database using php

I've annotated my code with the problem, any suggestions on solving this? Been stuck on it for a couple of hours now..

<?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");
?>

change

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

to

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


- The first problem is that $linv = mysql_fetch_array returns only the next row and stores it as an array in $linv , in the very beginning it starts with row # 0
So the first problem is that you were missing a loop to retrieve all rows

- Now you may ask your self "If I'm getting only one row so why the output was 1 1", this is because mysql_fetch_array accepts a second parameter which detriments the fetch mode (MYSQL_ASSOC for associative array which can be accessed only with columns names in the query, MYSQL_NUMERIC for numeric array which can be accessed only with numbers 0,1,2 ... in the same order columns are specified in the select clause), when you don't pass that parameter, then MYSQL_BOTH will be used by default and you will get the first row like that ["0" => "1" , "item_id" => "1"]
What you were doing is just looping through all the elements in the first row

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM