0

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;
}

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

+1 to note, just because you only select one value from MySQL doesn't mean it returns just that element, it's still a key=>value pair in an array.
+1 i thought he wanted to print the array, just the terms value from the query.
1

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];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.