Welcome Guest, Not a member yet? Register   Sign In
Populating an array from db?
#1

[eluser]PHP Creative[/eluser]
I have tired the following script to populate an array for a drop down menu.

Code:
<? $options = array( foreach ($query->result() as $row){
                  "1"  => "1",}
);
?>

Obviously the code above does not work. How do you do this in CI?

Many thanks.
#2

[eluser]Colin Williams[/eluser]
For starters, use proper PHP syntax. I have no clue what you are attempting there.
#3

[eluser]PHP Creative[/eluser]
Apologies. I am trying to populate an array from a database.
#4

[eluser]Dam1an[/eluser]
What format do you want the array to be, cause you can just return the result as an array
#5

[eluser]PHP Creative[/eluser]
The array has to be used in a drop down.

Code:
<?

$options = array(
             /////generated from database
                );


echo form_dropdown('users', $options);

?>
#6

[eluser]Dam1an[/eluser]
Sorry, jumped to the second post and just saw you wanted it as an array
Try
Code:
$results = // do query

// Create the array
$options = array();

// for each result, add it to the array
foreach($results as $result) {
    $options[$result->key] = $result->value;
}

echo form_dropdown('users', $options);
#7

[eluser]PHP Creative[/eluser]
I'm not entirely sure how that works...

Code:
<?    

$results = $this->db->get('users');

$options = array();

foreach($results as $result) {
    $options[$result->key] = $result->value;
}

echo form_dropdown('users', $options);

?>

I get the following error message "Message: Trying to get property of non-object"

Thanks a million.
#8

[eluser]Dam1an[/eluser]
you need to call ->result on the query line
Code:
// change this
$results = $this->db->get('users');
// to this
$query = $this->db->get('users');
if($query->num_rows() > 0) {
  $result = $query->result();
}
#9

[eluser]PHP Creative[/eluser]
Thats great, thanks very much once again :-)




Theme © iAndrew 2016 - Forum software by © MyBB