0

I need to keep one row value from table in bottom position in an array using PHP and MySQL. Here is my table:

db_designation:

id      name

1       aaa

2       bbbb

3       Other

4       tttt

My query is below:

$sqldeg=mysqli_query($connect,"select * from db_designation order by id desc");
while ($row=mysqli_fetch_array($sqldeg)) {
            $desdata[]=array("did"=>$row['id'],"dname"=>$row['name']);
}

Here I need this id->3 name->Other row from table value always come in last in the array i.e-$desdata.

2
  • I suggest you need another field on your table called Sequence or SortOrder or something, and ORDER BY that instead in your query. Commented Jul 17, 2017 at 11:03
  • I agree with ADyson that your data model does not adequately describe your data - however it should be named according the REASON you need this record to appear last or the fact it should appear last, not according to the method by which the outcome is achieved. Commented Jul 17, 2017 at 11:28

2 Answers 2

4

You could do it at query, with ordering before getting to php with.

By id:

ORDER BY (CASE WHEN `id`=3 THEN 1 ELSE 0 END) ASC, `id` DESC

Or by name:

ORDER BY (CASE WHEN `name`='Other' THEN 1 ELSE 0 END) ASC, `id` DESC

this will append 1 when id or name matches, otherwise zero (0), and will order in ASCENDING order.

So your query would be:

$sqldeg=mysqli_query($connect,"select * from db_designation ORDER BY (CASE WHEN `id`=3 THEN 1 ELSE 0 END) ASC, `id` DESC");
while ($row=mysqli_fetch_array($sqldeg)) {
            $desdata[]=array("did"=>$row['id'],"dname"=>$row['name']);
}
Sign up to request clarification or add additional context in comments.

Comments

0

Do like this

$others='';
$sqldeg=mysqli_query($connect,"select * from db_designation order by id desc");
while ($row=mysqli_fetch_array($sqldeg)) {
    if(strpos($row['name'], 'Other')===false)
        $desdata[]=array("did"=>$row['id'],"dname"=>$row['name']);
    else
        $others=array("did"=>$row['id'],"dname"=>$row['name']);
}
$desdata[]=$others;

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.