Sunteți pe pagina 1din 19

PHP and MySQL

Agenda
• Intro to MySQL
• Steps in using MySQL with PHP
• Working with MySQL Database
• DB Connection
• Performing DB operations in MySQL via PHP
• Outputting records in PHP via recordset
MySQL
– PHP can be used to connect to a Database
– We will be using MySQL database
– Recall to access dabase using EasyPHP:
– http://localhost/mysql
Steps in Using MySQL with PHP
The process of using MySQL with PHP:
1. Connect to MySQL mysql_connect
2. Select the database to use mysql_select_db
3. Build a query string $query = "SELECT * FROM
tableName";
4. Perform the query $result = mysql_query($query);
5. Retrieve the results and output it to a web page
• $rows = mysql_num_rows($result);
• $row = mysql_fetch_row($result);
6. Repeat Steps 3 to 5 until all desired data retrieved.
7. Disconnect from MySQL (usually done automatically)
Working with mysql database
• First a connection needs to be opened where
servername, username and password are
provided
mysql_connect(servername, username,
password)
• in the following code, the default user :”root”
and default password: no password have been
used.
• The “die” part is executed if the connection fails
Connection code –db_connect.php
<?php

$strHost = "localhost";
$strUser = "root";
$strPass = "";
$strDb = "webtech";

// open connection
$connection = mysql_connect($strHost, $strUser, $strPass) or
die("Unable to connect!");

?>
Opening a connection
• The next step involves selecting the database
that will be used.
mysql_select_db(“webtech”)
• Once again, the “die” part will be executed if
the database is not found.
mysql_select_db(“webtech”) or die(“could
not select database”);
Closing the connection
• The connection will be closed automatically
when the script ends
• To close the connection before, the
mysql_close() function is used:
mysql_close($connection);
Using SQL and PHP
• The mysql_query() function is used by PHP to
execute and SQL statement
• This function is used to send a query or command
to MySQL connection
• The example below stored the data returned by
the mysql_query() function in the $result variable
$result = mysql_query(“SELECT *FROM modules”)
or die(“Qurey failed: “. mysql_error());
Reading records from a query-
Recordset
• The mysql_fetch_array() function is used to
return the first row from the recordset as an
array
• Each call to mysql_fetch_array() returns the
next row in the recordset
mysql_fetch_array($result)
Looping through the recordset
• The while loop loops through all the records in
the recordset

While($row= mysql_fetch_array($result){

}
Printing the data
• To output the value of each row, the PHP $row
variables
• ($row[‘modulecode’] and $row[‘moduledesc’]
are used.

echo $row[‘modulecode’]
echo $row[‘moduledesc’]
Case Study(1)
• We are required to create a form –”modules.php” to
Add and View Modules as follows:

Add processModule.php View

• The above diagram shows the process of adding and


viewing of modules
Case Study(2)
• Database Details
– Host = "localhost";
– Username = "root";
– Password = "";
– Database = "webtech";
– Table : modules(Module_Code, Module_Desc)

• Forms:
– db_connect.php
– module.php
– processModule.php
processModule.php – add record
<?php
include("db_connect.php");

if (isset($_POST['btn_add'])){ // checking if button add was pressed

$moduleCode = $_POST["txt_moduleCode"]; // form inputs


$moduleName = $_POST["txt_moduleName"];

// create query
$query = "insert into modules values ('$moduleCode','$moduleName')";

// execute query
if(!mysql_query($query)){
header('location:formModule.php?add=no'); // form redirection
}
else {
header('location:formModule.php?add=yes'); // form redirection
}
}
processModule.php – view record
else if (isset($_POST['btn_view'])){// checking if button view was pressed

$result = mysql_query("Select * from modules") or die('Query Failed: '.mysql_error());

mysql_fetch_array($result);

echo "<table>"; // printing the table heading


echo "<tr><th>Module Code</th>";
echo "<th>Module Description</th></tr>";
while($row=mysql_fetch_array($result)){ // fetching the data
echo "<tr><td>".$row['Module_Code']."</td>";
echo "<td>".$row['Module_Name']."</td></tr>";

}
echo "</table>";
mysql_free_result($result);

}
mysql_close($connection);
?>
Exercise 1
• Modify the code above to fill in a drop down
menu with the module names
Exercise 2
• Create a “personalDetail” Form to register
personal details as follows:
PERSONALDETAILS FORM Database Details
DB Name : DataStore
Name txt_name Table Name: PersonalDetails(name,
Surname txt_surname surname,email,mobile,
username,password)
Email txt_email
Mobile txt_mobile On clicking the add button, the
Username txt_user addDetails.php form is called to insert
the necessary details in the above table.
Password txt_pwd

ADD Successful addition or error messages


are redirected to the same
Details successfully added ! personalDetail.php form
Exercise 2
• Create a “login.php” for login

LOGIN FORM Username and password are checked


against the records in the
Username txt_user personalDetails tables.
Password txt_pwd
On success, a session is started and the
LOGIN user is redirected to the welcome.php
Invalid user name and password! form which outputs the message
“Welcome $Username”

While on failure, a message appears


“invalid username and password” in the
login form itself

S-ar putea să vă placă și