You don't need the <div> tags there, you can just put the id attributes on the <td>
Change your query to something like this:
SELECT * FROM num where d IN (0,1) ORDER BY d
As for your while loop, you can't do what you want like that. PHP isn't Javascript, so once you've echoed something out, you can't go back and insert other things into a block just because it's got an id value.
What you can do is echo out up to the first cell you need to put things into, then start your loop. In the loop, just echo out the data you want until the value of d changes in a row in your loop. When that happens, echo out the HTML to close that cell and open another, then carry on with the loop. Finally, just close off the cell and the table and you're done.