Jump to content

array out of a database


Ryflex

Recommended Posts

Hi all,

 

This is a piece of code of my php page and what I need is that $n1 till $n4 is filled. Somehow only $n1 is filled.

Can anyone tell me what I'm doing wrong here.

 

Thnx Ryflex

 

$sql				= "SELECT name FROM unittype WHERE type = 1";
$result				= mysql_fetch_array(mysql_query($sql)) or die("Could not find units");
$n1					= $result[0];
$n2					= $result[1];
$n3					= $result[2];
$n4					= $result[3];
echo "$n1 <BR> $n2 <BR> $n3 <BR> $n4";

Link to comment
https://forums.phpfreaks.com/topic/221887-array-out-of-a-database/
Share on other sites

A) Don't use a series of named variables, $n1, $n2, ... Use an array (arrays are for sets of data, which is what you have.)

 

B) Instead of an echo statement, you would assign the value to an array element. Programming is about doing what you want when and where you want it to happen.

 

C) Done!

Hi all,

 

I got this far and got what is underneath but then how do I get the right values???

 

Thnx Ryflex

 

$sql				= "SELECT name FROM unittype WHERE type = 1";
$result				= mysql_query($sql) or die("Could not find units");
while($data = mysql_fetch_assoc($result))
{
$n[]				= $data;
}
print_r($n);
echo $n[0],$n[1],$n[2],$n[3];

Array ( [0] => Array ( [name] => gunner ) [1] => Array ( [name] => marine ) [2] => Array ( [name] => sniper ) [3] => Array ( [name] => special ops ) ) ArrayArrayArrayArray

Don't store the full array, only store the information you need:

<?php
$sql				= "SELECT name FROM unittype WHERE type = 1";
$result				= mysql_query($sql) or die("Could not find units");
while($data = mysql_fetch_assoc($result))
{
$n[]				= $data['name'];
}
print_r($n);
echo implode(',',$n);
?>

 

Ken

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.