If you want your server to send/receive SMS directly you need to add an SMS card to your server which has a SIM in it and an active account with a telco.
Alternatively, you can use an SMS gateway, where you pay to use someone else's hardware. The API's for sending and receiving SMS's are likely to vary depending on the gateway you choose.
Whichever of the above you choose, you will need to read the appropriate documentation to learn how to send/receive an SMS. Try simple sending and recieving to make sure you have it correct.
Once you have that done, querying the database is very standard stuff, and even has its own forum here.
I hope this helps?