开发者

Having an issue with SQL query... in PHP (very simple code)

开发者 https://www.devze.com 2023-01-23 01:40 出处:网络
Ok so basically my code isnt working as intended.. so i took it completely apart and even placed this query at the top of page; tried hardcoding in values and its still not working.This particular que

Ok so basically my code isnt working as intended.. so i took it completely apart and even placed this query at the top of page; tried hardcoding in values and its still not working. This particular query is supposed to return 5 rows of data to the $weapons array, but its not working.

$weapons_sql = "SELECT weapon_id, weapon_name, weapon_strength FROM Weapon_Info WHERE weapon_id BETWEEN 1 AND 5";
$weapons_query = mysql_query($weapons_sql);
$weapons = mysql_fetch_array($weapons_query);


print_r($weapons);

so weapon_id in the databse is a smallint(8) or something rather, (exact length im unsure of atm).. and it has 30 rows in the table, weapon_id ranging from 1-30

this particular snippet when run returns:

Array ( [0] => 1 [weapon_id] => 1 [1] => Humvee [weapon_name] => Humvee [2] => 100 [weapon_strength] => 100 )

I just don't understand it.. every other query in my entire project works save this one. Please help? I've also tried replacing BETWEEN operator with >= <= oper开发者_开发百科ators, which outputs the same results.


try

while($weapons = mysql_fetch_array($weapons_query)){
    print_r($weapons);
}

you need a loop like this to see all rows.


You are only fetching one row of the results. You need to loop through and collect all the results:

while(false !== ($row = mysql_fetch_array($weapons_query))) {
    $weapons[] = $row;
}

var_dump($weapons);

mysql_fetch_array only fetches one row of results at a time, as shown in the documentation. This means, for instance, that you can deal with sets of results that demand more memory than your script is allowed.


mysql_fetch_array returns only one row. You want to keep fetching arrays until you have all the rows:

$weapons_sql = "SELECT weapon_id, weapon_name, weapon_strength FROM Weapon_Info WHERE weapon_id BETWEEN 1 AND 5";
$weapons_query = mysql_query($weapons_sql);
$weapons = array();
while ($weapon = mysql_fetch_array($weapons_query))
{
    $weapons[] = $weapon;
}
print_r($weapons);
0

精彩评论

暂无评论...
验证码 换一张
取 消