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
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!

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.