Databases
- Written By
- PHPin24
- Submitted At
- 2008-02-05 01:09:40
- Num Views
- 849
- Category
- PHP
|
Connecting to a database sounds like a big step when you're just starting to code. To connect to a database you need the mysql_connect() command. mysql_connect() takes 5 parameters in total. You only need to worry about 3 at this point. mysql_select_db() takes 2 parameters in total. You only need 1 for now. The below code will connect to MySQL server and select a database. <?php mysql_connect($hostname,$username,$password); mysql_select_db($database); ?> $hostname - This is the IP address or name of the server. $username - The username to access the database. $password - The password to access the database. $database - This is the database name. The hostname is generally "localhost" if your website is running off a single server. What this means is that the database is on the same machine as your website. When using WAMP this is generally the case. So you are connected to a database... Now you need to perform a query. To perform a query you need the mysql_query() command. mysql_query() takes 2 parameters in total and returns one value. Once again you only need 1. <?php $sql = "SELECT * FROM users"; $result = mysql_query($sql); ?> $sql - Contains the MySQL query you want to run. $result - Contains a resource ID. This will return a resource id, this is just a link to where the actual data is. To get the values returned by the query you need to fetch the results from this resource. To do this you will use mysql_fetch_assoc(). mysql_fetch_assoc() takes 2 parameters in total and returns the data. You need 1 parameter. Generally queries return more than one result so you need to loop through the results. Let us say you have a column called `name` in your table called `users` in your database. <?php while($row = mysql_fetch_assoc($result)){ echo $row['name']; } ?> This will print out the names of the the users in the `users` table. That's it, your first database connection and query is done! Full Example <?php $database = "test_db"; $hostname = "localhost"; $username = "user"; $password = "123"; mysql_connect($hostname,$username,$password); mysql_select_db($database); $sql = "SELECT * FROM users"; $result = mysql_query($sql); while($row = mysql_fetch_assoc($result)){ echo $row['name']; } ?> Have fun... By PHPin24 @ 2008-02-05 01:09:40
|
