1

I am dumping some results from the database directly into tag in the html, how I can make the first option value to be null, and after that the database results to be sorted? This way I will have this drop down menu an option to not choose anything from it.

this is my code here:

<?php 
    $select = new Users;
    $stmt = $select->selecttema();
    while( $row = $stmt->fetch()){ 
        echo '<option value="' . $row['id'] . '">' . $row['topic'] . '</option>';
    } 
?>

3 Answers 3

3

Just

echo '<option value="">Select a topic</option>'

before the while loop.

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

Comments

3

actually Juan Pablo had answered the question. i just add something on his answer. if you add selected in your option it will be first option and you do not need to add data in value

echo '<option selected value="">Select a topic</option>';

Comments

2

To make an empty option:

<select>
    <option value="">Select</option>
<?php 
    $select = new Users;
    $stmt = $select->selecttema();
    while( $row = $stmt->fetch()){ 
        echo '<option value="' . $row['id'] . '">' . $row['topic'] . '</option>';
    } 
?>
</option>

You're not clear about what this Users object is or how you're fetching data so I'll just assume you're using a mySQL database, in which case you can use ORDER BY:

SELECT * FROM `users` WHERE 1 ORDER BY id DESC

For instance the above statement will select all users in the users database and order them by their id in descending order.

To sort the <select> options in JS, take a look at Sort Select Options by Value Attribute Using jQuery and Javascript to sort contents of select element

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.