Membership
Main Menu
Forum Boards
Stats
- 20 tutorials
- 74,814 members
- 734,875 forum posts
- 13 blog posts
Tutorials
PHP Basic Database Handling
Views: 67589
Dealing With The Database
The first half of the code we will handle all database interaction. We want to do this first, because we want all changes to be reflected on the list after we hit the submit button, when the page gets displayed again.
In order to do something with your database using PHP, you must first establish a connection to your database. That's just a really fancy way of saying you have to login to the database.
These first two lines are what we use to connect to and select your database. The mysql_connect function is what connects to the database. It takes 3 arguments: the host, the username for the database, and the password for the database.
Usually if you are running the script on the same server and you don't have weird access restrictions (like if you use one of those crappy "free" hosting services), simply putting 'localhost' as the host should work. A lot of server configurations add prefixes to your database username and database name, like phpfreak_crayonviolent for username and phpfreak_testdb for a database name (note: this name and dbname do not exist so don't bother trying to exploit, lol).
Your host should have some kind of documentation about whether prefixes are added to your stuff, or whether you have to use a specific host name instead of localhost. Talk to them if you need help.
mysql_select_db selects the database you want to use. You want to pick the one your table is in. It requires one argument: the database name. It optionally accepts a second argument, where you can specify the connection stream. I like to specify the connection stream, mostly out of habit.
The database connection (ideally) lasts as long as the script runs. I say "ideally" because hiccups happen. You can also tell PHP to close the connection with mysql_close($conn);. You do not have to supply an argument for it. If you do not supply a connection stream, it will close the last one opened (yes, that does mean you can have multiple connections opened at once). But again, PHP does automatically close the connection after the script finishes executing anyways, so to be honest, I usually don't bother with mysql_close($conn);.
