0

I have a MySQL result set

$fields_num = mysql_num_fields($result);

I would like to assign all of these results PHP variables that I can use on the page. What's the easiest way?

Thanks!

1
  • Do you mean get an array of results, or turn the array into individual variables? Your quoted piece of code would just tell you how many columns were returned. Commented Dec 25, 2010 at 0:41

3 Answers 3

4
$row = mysql_fetch_assoc($result);

Access via $row["name"]

$row = mysql_fetch_array($result);

Access via $row[0] and $row["name"]

Complete example...

$result = mysql_query("SELECT id, name FROM mytable");

while ($row = mysql_fetch_array($result)){
    echo $row[0];echo $row["name"];  
}

Will print "id" and "name".

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

Comments

2

Try mysql_fetch_array which return results as an array with column name as associate key

$row = mysql_fetch_array($result, MYSQL_ASSOC);
/* $row will be an array */
/* and the column wil be the associate key */

OR

you can use mysql_fetch_field, which provide even more information

Comments

0

If you are fetching multiple rows, you will need a while loop.

while($row = mysql_fetch_array($result)){
    echo $row['column_name'];
}

This will execute the code in the curly brackets for each row result. In the example, printing a field called 'column_name'.

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.