Jump to content

Archived

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

craygo

**SOLVED**Fill an array

Recommended Posts

I have a table and I want to put a couple fields into an array. I would like to query the table with my parameters then fill the array the keys will be one field and the values will be another field. I tried this but it is not correct

[code]<?php
$accounts = array();
$sql = "SELECT * FROM tokayacct";
  $res = mysql_query($sql) or die (mysql_error());
    while($r=mysql_fetch_assoc($res)){
$accounts[0] = $r['account_num'];
$accounts[1] = $r['meter_num'];
}
?>[/code]

thanks guys

Ray

Share this post


Link to post
Share on other sites
ok so account_num , meter_num , are in your table. You want this stored in an array.. maybe store it by id and put another array in there.

you could use something like:
[code]
<?php

$accounts = array();
$sql = "SELECT * FROM tokayacct";
  $res = mysql_query($sql) or die (mysql_error());
    while($r=mysql_fetch_assoc($res)){
    $accounts[$r[id]] = array($r['account_num'], $r['meter_num']);
}

?>
[/code]

something like that might work..

Share this post


Link to post
Share on other sites
The reason the OP's original code does not work is that the OP is constantly overlaying the first and second elements in the array.

Another way of doing this would be:
[code]<?php
$accounts = array();
$sql = "SELECT * FROM tokayacct";
  $res = mysql_query($sql) or die (mysql_error());
    while($r=mysql_fetch_assoc($res)){
    $accounts[$r['account_num']] = $r['meter_num'];
}?>[/code]

Which builds an array that is keyed by the account_number.

Ken

Share this post


Link to post
Share on other sites
<?php
Maybe like...

[code]
<?

$accounts = array ();

$sql = "SELECT * FROM tokayacct";

$res = mysql_query ( $sql ) or die ( mysql_error () );

while ( $r = mysql_fetch_assoc ( $res ) )
{
$accounts[$r['account_num']] = $r['meter_num'];
}

?>[/code]


me!

Share this post


Link to post
Share on other sites
Make a 2 dimensional array:
[code]<?php
$accounts = array();
$currow = 0; //initialize
$sql = "SELECT * FROM tokayacct";
  $res = mysql_query($sql) or die (mysql_error());
    while($r=mysql_fetch_assoc($res)){
        //2 dimensional array notation used below
        $accounts[$currow]['account_num'] = $r['account_num'];
        $accounts[$currow]['meter_num'] = $r['meter_num'];
        //add other fields you want to store here
        $currow++; //increment first array index
    }
?>[/code]

Share this post


Link to post
Share on other sites
Thanks for the replies fellas. Kens worked great.

Ray

Share this post


Link to post
Share on other sites

×

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.