Richard
Richard

Reputation: 3

PHP For Loop Printing An Array

This might seem like a really easy question but it has got me stumped lol. I am trying to print the rows received from the database. I want to store the rows inside an array and then print them using a for loop. I know that the query works however when I try to print the array elements it only prints the word array. I have tired doing it with a foreach loop and a simple for loop. If anyone can point me in the right direction would be a life saver.

Printing Php Code

<?php

    $type = "FREE";
    $free = getTerms($type);
    echo "<p>";
    for($j = 0; $j < count($free); $j++)
    {
    echo "start".$free[$j]."end";
    }
    echo "</p>";                        
?>

geting the rows from the database

function getTerms($type)
{
    $terms = array();
    $connection = mysql_open(); 
    $query = "select terms from terms_and_con where accountType='$type' && currentTerms='YES'";
    $results = mysql_query($query, $connection) or show_error("signUp.php", "", "");

    while($row = mysql_fetch_array($results))
    {
       $terms[] = $row;
    }
    mysql_close($connection) or show_error("signUp.php", "", "");
    return $terms;
}

Upvotes: 0

Views: 321

Answers (2)

Tadej Magajna
Tadej Magajna

Reputation: 2963

the thing is function mysql_fetch_array ( as the name suggests) returns an ( in your case both associative and number) array. so $row is actually array(0 => VALUE, 'terms' => 'VALUE')

So what you are trying to echo is actually an array.

Simple fix: replace:

$terms[] = $row;

with:

$terms[] = $row[0];

Upvotes: 1

Phil
Phil

Reputation: 165069

Each entry in the $free array is itself an array (from $row).

Try

echo 'start', $free[$j]['terms'], 'end';

Alternatively, you may find a foreach loop more semantically appropriate

foreach ($free as $row) {
    echo 'start', $row['terms'], 'end';
}

Edit: I'd advise using mysql_fetch_assoc() instead of mysql_fetch_array() if you're only going to use associative entries from $row.

Upvotes: 5

Related Questions