120 likes | 135 Views
PHP AND MYSQL. PHP and MySQL. PHP has functions that allow access to MySQL Databases Access is very easy 1. Connect 2. Select Database 3. Query 4. Close connection. 1. Connect. $link = mysql_connect('mysql_server', 'mysql_user',
E N D
PHP and MySQL • PHP has functions that allow access to MySQL Databases • Access is very easy • 1. Connect • 2. Select Database • 3. Query • 4. Close connection
1. Connect $link = mysql_connect('mysql_server', 'mysql_user', 'mysql_password');
2. Select Database $link = mysql_connect('mysql_server', 'mysql_user', 'mysql_password'); $db_selected = mysql_select_db('foo', $link);
3. Query $link = mysql_connect('mysql_server', 'mysql_user', 'mysql_password'); $db_selected = mysql_select_db('foo', $link); $result = mysql_query("DELETE FROM table;", $link);
4. Close $link = mysql_connect('mysql_server', 'mysql_user', 'mysql_password'); $db_selected = mysql_select_db('foo', $link); $result = mysql_query("DELETE FROM table;", $link); mysql_close($link);
mysql_query • INSERT, UPDATE, DELETE, DROP • Returns true or false • SELECT • Returns resource on success, false on error • The returned resource should be passed to mysql_fetch_array()
Retrieving Table $link = mysql_connect('mysql_server', 'mysql_user', 'mysql_password'); $db_selected = mysql_select_db('foo', $link); $result = mysql_query("SELECT * FROM table;", $link); while ($row = mysql_fetch_array($result)) { print($row[0]); print($row[1]); } mysql_close($link);
Retrieving Table $link = mysql_connect('mysql_server', 'mysql_user', 'mysql_password'); $db_selected = mysql_select_db('foo', $link); $result = mysql_query("SELECT * FROM table;", $link); while ($row = mysql_fetch_array($result)) { print($row["id"]); print($row["name"]); } mysql_close($link);
Error Handling • Every function in the previous code examples could fail • Connection can fail, sql query can fail etc. • Usually you exit the script when DB fails. • With exit($status) – function, you can stop the execution of the script.
Example of Error Handling 1 $link = mysql_connect('mysql_server', 'mysql_user', 'mysql_password'); if( ! $link ) { exit("Error connecting to database"); }
Example of Error Handling 2 $link = mysql_connect('mysql_server', 'mysql_user', 'mysql_password') or exit("Error connecting to database");