1

I am doing some work that requires me to add the data from a specific column, say Column 1, to a PHP array. I can get the data from the first row in Column 1, but it stop there. How do I collect that columns data from every row in the table?

3
  • SELECT RowName FROM Table Commented Dec 20, 2010 at 1:09
  • Ok @Stefan H... How do I display this data? Commented Dec 20, 2010 at 1:10
  • Display as in print the html? Commented Dec 20, 2010 at 1:14

2 Answers 2

4

You have to loop over the result set in a while loop:

$result = mysql_query('SELECT...');

$data = array();
while(($row = mysql_fetch_array($result))) {
    $data[] = $row['columnName'];
}

Every call to mysql_fetch_array will get the next row of the result set. If there is no row anymore, it will return null and the loop stops.

The documentation provides good examples.

Update:

Regarding duplicates: Either specify your SQL query correctly (preferred), e.g.

SELECT DISTINCT columnName FROM table

or use array_unique after you fetched all the data:

$data = array_unique($data);
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome! Thanks, you wouldn't happen to know how I would remove duplicates from that array? Would you?
1
    //Variable declaration as a small sql query
    $query = "select RowName FROM Table;";
    //Execute Query
    $result = mysql_query($query);
    while ($row = mysql_fetch_assoc($result))
    {
                 //Do Stuff
             }

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.