Jump to content

**SOLVED**Fill an array


craygo

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
Link to comment
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..
Link to comment
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
Link to comment
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]
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.