1

I am using a simple for loop to print field names of a table and it didn't work but the same code when I wrote using foreach loop it worked perfectly fine. I am a bit confused as to what might have caused it. Please help me find where I went wrong with the coding.

Code using foreach-loop:

$data=mysqli_query($con,"select * from `address` order by $id $sort");
echo "<tr>";
    $field=mysqli_fetch_fields($data);
    foreach ($field as $val) {
        echo "<th><a href='sort_table_data_asc_desc.php?fn=$val->name &ord=$sort'>$val->name</a></th>";
    }
echo "</tr>";

Output: as requested

enter image description here

Code using for-loop:

$data=mysqli_query($con,"select * from `address` order by $id $sort");
$col=mysqli_num_fields($data);
echo "<tr>";
    $field=mysqli_fetch_fields($data);
    for ($i=0;$i<$col;$i++) {
        echo "<th><a href='sort_table_data_asc_desc.php?fn=$field->name &ord=$sort'>$field->name</a></th>";
    }
echo "</tr>";

Output: as requested

enter image description here

2
  • Can you edit to show the expected output and what you actually got? Commented Dec 19, 2017 at 19:36
  • @Nick added the images as per your request Commented Dec 19, 2017 at 19:43

1 Answer 1

2

mysqli_fetch_fields returns an array of the fields, so you need to reference the array element when accessing the values

echo "<th><a href='sort_table_data_asc_desc.php?fn={$field[$i]->name}&ord=$sort'>{$field[$i]->name}</a></th>";

As you can see, I'm using $field[$i] at each point you access the fields coming back from mysqli_fetch_fields

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

6 Comments

I did what you said but it throws an error, "Object of class stdClass could not be converted to string"
I've updated it to include {} round the field, it makes the field itself clearer, can you try that
I've just tried it on a table I have and it works OK, have you changed both references to $field?
Yes @Nigel, I changed both the references in the URL as you said but it didn't work on my end.
If the error is giving a particular line of code that's showing the error, can you make sure that is in the code on your original question.
|

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.