Download presentation
Presentation is loading. Please wait.
1
PHP: Database connection
FdSc Module 109 Server side scripting and Database design 2011
2
Connecting PHP to MySQL
MySQL connection is done with the function mysql_connect Selecting a database is done with the function mysql_select_db
3
mysql_connect This needs three parameters: The host name The user name
The password Use the following variables and set their values appropriately: $hostname = “localhost"; $username = “MISNumber"; $password = "YOUR_PASSWORD";
4
PHP variables All PHP variables must Start with $
Contain alphanumeric characters or the underscore Must begin with a letter or an underscore $username = “MISNumber" both declares and assigns the value to the variable PHP is loosely typed: variables do not need separate declaration
5
mysql_connect Mysql_connect is a function
It takes three parameters and returns a value Either a valid SQL link identifier which PHP sees as TRUE Or FALSE if the connection failed $dbConnected = mysql_connect($hostname, $username, $password); The returned value will be assigned to the variable $dbConnected If successful we will use it later If it fails we will trap the error
6
mysql_select_db This needs two parameters: The database name
The valid SQL link identifier returned from mysql_connect Use the following variable and set its value appropriately: $databaseName = “MISNumber_library"; $dbSelected = mysql_select_db ($databaseName,$dbConnected); $dbSelected will be TRUE if the database has been selected
7
connection.php <?php
//error_reporting(0); // Suppresses MySQL error messsages. Can also in front of each command. $hostname = “localhost"; $username = “MISNumber"; //$password = "YourPassword"; //$databaseName = “MISNumber_library"; $dbConnected = mysql_connect($hostname, $username, $password); $dbSelected = mysql_select_db ($databaseName,$dbConnected); if ($dbConnected) { echo "MySQL connected OK<br /><br />"; //HTML syntax can be included in the echo string if ($dbSelected) { echo "DB Connected OK<br /><br />"; } else { echo "DB Connected FAILED<br /><br />"; } echo "MySQL connection FAILED<br /><br />"; ?>
8
File headers It is important to document what each php script does in a file header We can use a comment block to do this We start a comment block with /* and end it with */ This allows multi line comments Single line comments just start with //
9
File header example /* File: connection.php By: Bob Date: This script connects to a database */
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.