Tuesday, September 22, 2009

PHP Database Example - MySQL

This is a simple php Database example illustrating the basics such as creating an SQL query, fetching and updating a database. For this example we will be using a MySQL Database. However, this will work with any database. This example will use commands such as mysql_connect, mysql_fetch_object, mysql_query etc.

First lets have a look at the example. It's self explanatory.
 1. <?php
 2. try{
 3.     mysql_connect("localhost", "user1", "pwd");
 4.     mysql_select_db("mydatabase");
 5. }catch(Exception $e){
 6.     echo mysql_error();
 7.     exit;
 8. }
 9. /*Select*/
10. $result = mysql_query('select * from user_table');
11. 
12. while($row = mysql_fetch_object($result)) {
13.   echo "$row->id $row->first_name $row->address\n"; 
14. }
15. 
16. /*Update*/
17. $result=mysql_query("update user_table set first_name='barbie' where id=100");
18. 
19. mysql_close();
20. 
21. ?>
Hide line numbers

No comments: