SQL for Beginners: Part 3 (with links to parts 1 and 2)

http://net.tutsplus.com/tutorials/databases/sql-for-beginners-part-3-database-relationships/



Placement of Sandbox Folder

On Mac -> MAMP/htdocs
On Windows -> WAMP/htdocs

PHP and MySQL Database Interaction Steps


1. Create a connection.
2. Select a database.
3. Perform a database query.
4. Use returned data, if any.
5. Close the connection.

PHP Syntax for Database Interaction Steps


<?php
1. Create a database connection
connection is the handler - make sure to test for successful connection
$connection = mysql_connect("localhost", "root", "root");
if(!$connection) {
die("Database connection failed: " . mysql_error());
}
 
2. Select a database to use
$db_select = mysql_select_db("widget_corp", $connection);
if(!$db_select) {
die("Database selection failed: " . mysql_error());
}
?>
 
<!DOCTYPE html PUBLIC "-W3CDTD XHTML 1.0 StrictEN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Databases PHP</title>
<link rel="stylesheet" type="text/css" href="style.css"/>
<script type="text/javascript" src="script.js"></script>
</head>
 
<body>
<?php
3. Perform the database query
$result = mysql_query("SELECT * FROM subjects", $connection);
if(!$result) {
die("Database query failed: " . mysql_error());
}
 
4. Use returned data
while($row = mysql_fetch_array($result)) {
echo $row[2]." ".$row[1]."<br />";
echo $row["position"]." ".$row["menu_name"]."<br />";
}
?>
</body>
 
</html>
<?php
5. Close database connection
mysql_close($connection);
?>