Basic PHP MySQL
Basic PHP MySQL
Table of Contents
Item 1. Introduction 2. Basic PHP Syntax 3. PHP Operators 4. Conditional statement 5. Looping 6. PHP Functions 7. PHP Form Handling 8. The $ GET Variable 9. The $ POST Variable 10. The $ REQUEST Variable 11. PHP Sessions 12. PHP Cookies 13. Tutorial
Page 3 3 7 8 10 13 16 17 18 18 19 20 21
1. Introduction
PHP stands for PHP: Hypertext Preprocessor PHP is a server-side scripting language, like ASP PHP scripts are executed on the server PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, etc.) PHP is an open source software (OSS) PHP is free to download and use
1.1 What is a PHP File? PHP files may contain text, HTML tags and scripts PHP files are returned to the browser as plain HTML PHP files have a file extension of ".php", ".php3", or ".phtml" PHP is compatible with almost all servers used today (Apache, IIS, etc.) PHP is FREE to download from the official PHP resource: www.php.net
There are two basic statements to output text with PHP: echo and print. In the
example above we have used the echo statement to output the text " UiTM Johor ". Note: The file must have the .php extension. In file with the .html extension, the PHP code will not be executed.
2.1 Comments in PHP In PHP, we use // to make a single-line comment or /* and */ to make a large comment block. <html> <body> <?php 1/This is a comment /* This is a comment block */ ?> </body> '</html> 2.2 Variables in PHP Variables are used for storing a values, like text strings, numbers or arrays. When a variable is set it can be used over and over again in your script All variables in PHP start with a $ sign symbol. The correct way of setting a variable in PHP: $var_name = value; New PHP programmers often forget the $ sign at the beginning of the variable. In that case it will not work. Let's try creating a variable with a string, and a variable with a number: <?php $txt = "JKA"; $number = 1517; ?>
In PHP a variable does not need to be declared before being set. In the example above, you see that you do not have to tell PHP which data type the variable is. PHP automatically converts the variable to the correct data type, depending on how they are set. In a strongly typed programming language, you have to declare (define) the type and name of the variable before using it. In PHP the variable is declared automatically when you use it.
2.4 Variable Naming Rules
A variable name must start with a letter or an underscore "_" A variable name can only contain alpha-numeric characters and underscores (a-Z, 0-9, and _ ) A variable name should not contain spaces. If a variable name is more than one word, it should be separated with underscore ($my_string), or with capitalization ($myString)
String variables are used for values that contains character strings. In this tutorial we are going to look at some of the most common functions and operators used to manipulate strings in PHP. After we create a string we can manipulate it. A string can be used directly in a function or it can be stored in a variable. Below, the PHP script assigns the string " UiTM " to a string variable called $txt:
-
The output of the code above will be: UiTM Now, lets try to use some different functions and operators to manipulate our string.
FSKM 2009
If we look at the code above you see that we used the concatenation operator two times. This is because we had to insert a third string. Between the two string variables we added a string with a single character, an empty space, to separate the two variables.
The strlen() function is used to find the length of a string. Let's find the length of our string "Hello world!":
<?php
echo strlen("Mohd Lezam Lehat"); ?> The output of the code above will be: 16 The length of a string is often used in loops or other functions, when it is important to know when the string ends. (i.e. in a loop, we would want to stop the loop after the last character in the string)
2.8 Using the strpos() function
The strpos() function is used to search for a string or character within a string. If a match is found in the string, this function will return the position of the first match. If no match is found, it will return FALSE. 6
Let's see if we can find the string "world" in our string: <?php echo strpos("Hello world!","world"); ?> The output of the code above will be: ;6 As you see the position of the string "world" in our string is position 6. The reason that it is 6, and not 7, is that the first position in the string is 0, and not 1.
3. PHP Operators
This section lists the different operators used in PHP.
3.1 Arithmetic Operators Operator ;Description Example
+
' -
'Addition
x=2 x+2 x=2 5-x x=4 x*5 15/5 5/2 5%2 10%8 10%2 x=5 x++ x=5 x--
Result 4
Subtraction
i I
i
_J
3
20
*
I
Multiplication Division
3
2.5
-7
I
oh)
..
1 2
++
--
;Increment 1Decrement I
x=6 x=4
Example
+= -= I*=
V=
Oh =
x%=y
x=x%y
3.3 Comparison Operators Operator Description jis equal to != is not equal is greater than is less than >= <= is greater than or equal to is less than or equal to 'Example
,5==8 returns false 5!=8 returns true 5>8 returns false 5<8 returns true 5>=8 returns false 5<=8 returns true
3.4 Logical Operators Operator Description && and Example x=6 y= 3 (x < 10 && y > 1) returns true
or
not
4. Conditional statement
4.1 The If...Else Statement If you want to execute some code if a condition is true and another code if a condition is false, use the if....else statement. Syntax if (condition)
code to be executed if condition is true;
else code to be executed if condition is false; Example The following example will output "Have a nice weekend!" if the current day is Friday, otherwise it will output "Have a nice day!":
i<html>
1<body>
<?php 1$d=date("D"); if ($d=="Fri") echo "Have a nice weekend!"; !else echo "Have a nice day!"; ?> </body> </html> If more than one line should be executed if a condition is true/false, the lines should be enclosed within curly braces: <html> <body> <?php $d=date("D"); if ($d=="Fri") echo "Hello!<br />"; echo "Have a nice weekend!"; echo "See you on Monday!"; } ?> </body> </html>
4.2 The ElseIf Statement If you want to execute some code if one of several conditions are true use the elseif statement Syntax if (condition) code to be executed if condition is true; elseif (condition) code to be executed if condition is true; else code to be executed if condition is false; Example The following example will output "Have a nice weekend!" if the current day is Friday, and "Have a nice Sunday!" if the current day is Sunday. Otherwise it will output "Have a nice day!":
<html> <body> <?php $d=date("D"); if ($d=="Fri") echo "Have a nice weekend!"; elseif ($d=="Sun") echo "Have a nice Sunday!"; else echo "Have a nice day!"; 1?> </body> </html>
5. Looping
Very often when you write code, you want the same block of code to run a number of times. You can use looping statements in your code to perform this. In PHP we have the following looping statements: while - loops through a block of code if and as long as a specified condition is true do...while - loops through a block of code once, and then repeats the loop as long as a special condition is true for - loops through a block of code a specified number of times foreach - loops through a block of code for each element in an array
5.1 The for Statement The for statement is the most advanced of the loops in PHP. In it's simplest form, the for statement is used when you know how many times you want to execute a statement or a list of statements. Syntax for (init, cond, Inc)
code to be executed;
Parameters: init: Is mostly used to set a counter, but can be any code to be executed once at the beginning of the loop statement. cond: Is evaluated at beginning of each loop iteration. If the condition evaluates to TRUE, the loop continues and the code executes. If it evaluates to FALSE, the execution of the loop ends.
10
incr: Is mostly used to increment a counter, but can be any code to be executed at the end of each loop.
Note: Each of the parameters can be empty or have multiple expressions separated by commas. cond: All expressions separated by a comma are evaluated but the result is taken from the last part. This parameter being empty means the loop should be run indefinitely. This is useful when using a conditional break statement inside the loop for ending the loop.
Example The following example prints the text "Hello World!" five times:
1 <html>
<body> <?php
{
echo "Hello World!<br />";
}
?> </body>
</html>
5.2 The while Statement The while statement will execute a block of code if and as long as a condition is true. Syntax while (condition)
code to be executed,
Example The following example demonstrates a loop that will continue to run as long as the variable i is less than, or equal to 5. i will increase by 1 each time the loop runs: <html> <body> <?php $i=1; while($i<=5)
{
echo 'The number is " . $i . "<br />"; $i++;
}
?>
11
</body> </html>
53 The do...while Statement The do...while statement will execute a block of code at least once - it then will repeat the loop as long as a condition is true. Syntax Do
{
code to be executed;
}
while (condition); Example The following example will increment the value of i at least once, and it will continue incrementing the variable i as long as it has a value of less than 5: <html> <body> <?php $i=0; do
{
II
$i . "<br />";
12
6. PHP Functions
A function is a block of code that can be executed whenever we need it. Creating PHP functions: All functions start with the word "function()" Name the function - It should be possible to understand what the function does by its name. The name can start with a letter or underscore (not a number) Add a "{" - The function code starts after the opening curly brace Insert the function code Add a "}" - The function is finished by a closing curly brace
Example
A simple function that writes my name when it is called: r 1 <html> !<body> <?php function writeMyName() { echo "Mohd Lezam Lehat"; } ,writeMyName(); 1?. </body> </html>
echo " Mohd Lezam Lehat "; echo "Hello world! <br />"; echo "My name is "; writeMyName(); echo ".<br />That's right, "; writeMyName(); echo " is my name."; ?> </body> </html> The output of the code above will be:
13
Hello world!
My name is Mohd Lezam Lehat. That's right, Mohd Lezam Lehat is my name.
6.1 PHP Functions - Adding parameters Our first function (writeMyName()) is a very simple function. It only writes a static string. To add more functionality to a function, we can add parameters. A parameter is just like a variable. You may have noticed the parentheses after the function name, like: writeMyName(). The parameters are specified inside the parentheses. Example 1 The following example will write different first names, but the same last name: <html> <body> <?php
echo "My name is "; writeMyName("Mohd Lezam"); .echo "My name is "; writeMyName("Norleza"); echo "My name is "; 'writeMyName("Mohd Sufian"); ?> </body> </html> The output of the code above will be: My name is Mohd Lezam Lehat. My name is Norleza Lehat. My name is Mohd Sufian Lehat. Example 2 The following function has two parameters: <html> <body>
14
echo "My name is "; writeMyName("Mohd Lezam","."); echo "My name is "; writeMyName("Norleza","!"); echo "My name is "; writeMyName("Mohd Sufyan","..."); ?> </body> </html> The output of the code above will be: My name is Mohd Lezam Lehat. My name is Norleza Lehat! My name is Mohd Sufian Lehat... 6.2 PHP Functions - Return values Functions can also be used to return values. <html> <body> <?php function add($x,$y) { $total = $x + $y; return $total;
}
echo "1 + 16 = " . add(1,16); ?> </body> </html> The output of the code above will be: 1 + 16 = 17
15
<html> <body> <form action="welcome.php" method="post"> Name: <input type="text" name="name" /> Age: <input type="text" name="age" /> '<input type="submit" /> </form> </body> </htnnl>
,
The example HTML page above contains two input fields and a submit button. When the user fills in this form and click on the submit button, the form data is sent to the "welcome.php" file. The "welcome.php" file looks like this: <html> <body> Welcome <?php echo $_POST["name"]; ?>.<br /> You are <?php echo $_POST["age"]; ?> years old. </body> </html> A sample output of the above script may be: Welcome John. You are 28 years old.
16
<form action="welcome.php" method="get"> Name: <input type="text" name="name" /> lAge: <input type="text" name="age" /> '<input type="submit" /> I</form> When the user clicks the "Submit" button, the URL sent could look something like this: http://www.w3schools.com/welcome.php?name=Peter&age=37 The "welcome.php" file can now use the $_GET variable to catch the form data (notice that the names of the form fields will automatically be the ID keys in the $_GET array): Welcome <?php echo $_GET["name"]; ?>.<br /> You are <?php echo $_GET["age"]; ?> years old!
8.1 Why use $_GET? Note: When using the $_GET variable all variable names and values are displayed in the URL. So this method should not be used when sending passwords or other sensitive information! However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases. Note: The HTTP GET method is not suitable on large variable values; the value cannot exceed 100 characters.
17
9.1 Why use $_POST? Variables sent with HTTP POST are not shown in the URL Variables have no length limit
However, because the variables are not displayed in the URL, it is not possible to bookmark the page.
18
Before you can store user information in your PHP session, you must first start up the session.
Note: The session_start() function must appear BEFORE the <html> tag:
1<?p h p session_start(); ?> <html> <body> </body> </html> The code above will register the user's session with the server, allow you to start saving user information, and assign a UID for that user's session.
11.2 Storing a Session Variable
The correct way to store and retrieve session variables is to use the PHP $_SESSION variable: <?php session_start(); // store session data $_SESSION[views']=1; ?> 1<html> <body> <?php //retrieve session data echo "Pageviews=". $_SESSIONNiewsl; ?> </body> </html> Output: Pageviews=1 In the example below, we create a simple page-views counter. The isset() function checks if the "views" variable has already been set. If "views" has been set, we can increment our counter. If "views" doesn't exist, we create a "views" variable, and set it to 1:
19
<?php
session_start(); if(isset($_SESSION[views1)) $_SESSION['views1=$_SESSION[views1+1; else $_SESSION[views']=1; echo "Views=". $_SESSION['views']; ?>
11.3 Destroying a Session If you wish to delete some session data, you can use the unset() or the session_destroy() function. The unset() function is used to free the specified session variable: <?php unset($_SESSION['views']); ?> You can also completely destroy the session by calling the session_destroy() function: <?php session_destroy(); 7> Note: session_destroy() will reset your session and you will lose all your stored session data.
20
Syntax
In the example below, we will create a cookie named "user" and assign the value "Alex Porter" to it. We also specify that the cookie should expire after one hour: <?php setcookie("user", "Alex Porter", time()+3600); ?> <html>
Note: The value of the cookie is automatically URLencoded when sending the
cookie, and automatically decoded when received (to prevent URLencoding, use setrawcookie() instead).
Example 2
You can also set the expiration time of the cookie in another way. It may be easier than using seconds. <?php $expire=time()+60*60*24*30; setcookie("user", "Alex Porter", $expire); ?> <html>
In the example above the expiration time is set to a month (60 sec * 60 min * 60 hours * 30 days).
The PHP $_COOKIE variable is used to retrieve a cookie value. In the example below, we retrieve the value of the cookie named "user" and display it on a page: <?php // Print a cookie echo $_COOKIE[" user"]; // A way to view all cookies print_r($_COOKIE); ?>
21
In the following example we use the isset() function to find out if a cookie has been
set: <html> <body> <?php if (isset(S_COOKIEruser"D) echo "Welcome " . $_COOKIE["user"] . "!<br />"; else echo "Welcome guestl<br />"; ?> </body> </html>
When deleting a cookie you should assure that the expiration date is in the past. Delete example: <?php // set the expiration date to one hour ago isetcookie(" user", "", timeQ-3600); 1?>
22
13. Tutorial
1. Basic Coding a) la.php <?php echo "Welcome to the UiTM"; print "Johor"; ?>
b)1'
<?php $txtl ="PHP"; $txt2="Programming"; $no1=2009; echo $txtl . " " . $txt2 . $nol; ?> c) 1 <?php $txt1="DON'T"; $bd2="ACT"; $txt3="AGE"; echo $txt1 . " always " . $txt2." </br> your".$b(t3; ?>
2.
Ope a)
,
<?php $no1=4; $no2=3; $total=$nol+$no2; echo "4 + 3 =".$total; ?> b) 2 <?php $rm=100; $dollar=3.88; $convert=$rm/$dollar; ?> Value in <b>RM</b> : <?php echo $convert; ?> 23
3.
24
4.
Function a) 4a.php <html> <body> <?php function Name() { echo "Mohd Lezam Lehat"; } Name(); ?> <?php Name(); ?> </body> </html>
a) 4a.php <?php function kira($no) { $jumlah=$no+3; echo "Jumlah : ". $jumlah; } kira(3); ?>
25
5.
Form a) 5a.php <form action="5ab.php" method="post"> Name: <input type="text" name="name" /> Gender: <select name="gender" id="gender"> <option value="Male">Male</option> <option value="Female">Female</option> </select> <input type="submit" value="Submit"/> </form>
<p>Name: <?php $nama = $_POST["name"]; $gender = $___POST["gender"]; echo $nama ?> </p> <p>Gender : <?php echo $gender ?> </P>
26
EXERCISE
DATABASE : dbComplaint
Staff(staffID name,email,password,type)
(Type : admin,IT,lecturer)
Complaint(complaintID,staffID,date,detail,location,category,status,dateAssign,dateComplete)
(Status :Pending,In-progress,Success,rejected)
Category(categorvID,name) eg: software,hardware
A. STAFF i) Submit Complaint date DATE STAFF ID DETAIL LOCATION CATEGORY Choose Category
Submit
ID 1 2 1
PERSON IN
Choose Category
ACTION
Submit
Ahmad
Choose Category Y
Submit
List Only Staff from IT ii)View complaint details DATE STAFF II) DETAIL
12102.' 2012
(tips:update)
LOCATION A101
CATEGORY Software
fd
Mg
TABLE OF CONTENT
MySQL for Beginner 1. Introduction 2. Installation 3. SQL statement - Connect - Create - Insert - Select - Where - Order By - Update - Delete 4. Getting Started With phpMyAdmin 3 4 6 6 6 8 9 9 9 10 10 11
1. Introduction to MySQL
MySQL is a database. The data in MySQL is stored in database objects called tables. A table is a collections of related data entries and it consists of columns and rows. Databases are useful when storing information categorically. A company may have a database with the following tables: "Employees", "Products", "Customers" and "Orders".
A database most often contains one or more tables. Each table is identified by a name (e.g. "Customers" or "Orders"). Tables contain records (rows) with data. Below is an example of a table called "Persons":
LastName (FirstName Address r----City
, la Move IR; a r i
The table above contains three records (one for each person) and four columns (LastName, FirstName, Address, and City).
1.2 Queries
A query is a question or a request. With MySQL, we can query a database for specific information and have a recordset returned. Look at the following query: SELECT LastName FROM Persons The query above selects all the data in the "LastName" column from the "Persons" table, and will return a recordset like this:
LastName
If you don't have a PHP server with a MySQL Database, you can download MySQL for free here: http://www.mysql.com/downloads/index.html
2. Installation
2.1 Installing MySQL on Windows For the Essentials and Complete packages in the MSI installer, you can select individual components to be installed by using the Custom mode, including disable the components confiurated for installation by default. Full details on the components are suggested uses are provided below for reference: Windows Essentials this package has a file name similar to mysqlessential-5.1.42-win32.msi and is supplied as a Microsoft Installer (MSI) package. The package includes the minimum set of files needed to install MySQL on Windows, including the MySQL Server Instance Config Wizard. This package does not include optional components such as the embedded server, developer headers and libraries or benchmark suite. Windows MSI Installer (Complete) this package has a file name similar to mysql-5.1.42-win32.zip and contains all files needed for a complete Windows installation, including the MySQL Server Instance Config Wizard. This package includes optional components such as the embedded server and benchmark suite. Without installer this package has a file name similar to mysql-noinstall5.1.42-win32.zip and contains all the files found in the Complete install package, with the exception of the MySQL Server Instance Config Wizard. This package does not include an automated installer, and must be manually installed and configured.
The Essentials package is recommended for most users. Both the Essentials and Complete distributions are available as an .msi file for use with the Windows Installer. The Noinstall distribution is packaged as Zip archives. To use Zip archives, you must have a tool that can unpack .zip files.
Dov..nk ad NISI
Run \ISI
l\ lyS (} 1..
Run AlrSQL
Regislci
Nly';(/1
Figure 2.1. Installation Workflow for Windows using MSI The workflow for installing using the MSI installer is shown below:
I )ownIcad Zip
10
,;
1 /gyp
Renmuc Directory
NIN.1QL
10:
I sc
3. SQL
SQL is short for Structured Query Language and is a widely used database
language, providing means of data manipulation (store, retrieve, update, delete) and database creation. Almost all modern Relational Database Management Systems like MS SQL Server, Microsoft Access, MSDE, Oracle, DB2, Sybase, MySQL, Postgres and Informix use SQL as standard database language. Now a word of warning here, although all those RDBMS use SQL, they use different SQL dialects. For example MS SQL Server specific version of the SQL is called T-SQL, Oracle version of SQL is called PL/SQL, MS Access version of SQL is called JET SQL, etc.
Syntax
mysql_connect(servername,username,password);
Parameter servername
Username Password
Description
Optional. Specifies the server to connect to. Default value is "localhost:3306" Optional. Specifies the username to log in with. Default value is the name of the user that owns the server process Optional. Specifies the password to log in with. Default is ""
Note: There are more available parameters, but the ones listed above are the most
important.
Syntax
CREATE DATABASE database_name
Example
CREATE DATABASE dBase
Syntax
CREATE TABLE table_name column_name1 data_type, column_name2 data_type, column_name3 data_type,
Example
CREATE TABLE Persons
( person ID int, name varchar(30), address varchar(50), age int(3)
DATE - A date.
DATETIME - date and time combination. TIMESTAMP - useful for recording the date and time of an INSERT or UPDATE operation. TIME - A time
3.3.2 Primary Keys and Auto Increment Fields Each table should have a primary key field. A primary key is used to uniquely identify the rows in a table. Each primary key value must be unique within the table. Furthermore, the primary key field cannot be null because the database engine requires a value to locate the record. The following example sets the personlD field as the primary key field. The primary key field is often an ID number, and is often used with the AUTO_INCREMENT setting. AUTO_INCREMENT automatically increases the value of the field by 1 each time a new record is added. To ensure that the primary key field cannot be null, we must add the NOT NULL setting to the field. Example CREATE TABLE Persons ( personlD int NOT NULL AUTOINCREMENT, PRIMARY KEY(personlD), name varchar(30), address varchar(50), age int );
3.4 Insert Data Into a Database Table The INSERT INTO statement is used to add new records to a database table. Syntax INSERT INTO table_name VALUES (valuel, value2, value3,...) The second form specifies both the column names and the values to be inserted: INSERT INTO table_name (column1, column2, column3,...) VALUES (valuel, value2, value3,...)
Example
INSERT INTO Persons (name, address, age) VALUES ('Ahmad', rJementah', 1 35 1 )");
3.5 Select Data From a Database Table
The following example selects all the data stored in the "Persons" table (The * character selects all the data in the table): SELECT * FROM Persons
The WHERE clause is used to extract only those records that fulfill a specified criterion.
Syntax
The ORDER BY keyword is used to sort the data in a recordset. The ORDER BY keyword sort the records in ascending order by default. If you want to sort the records in a descending order, you can use the DESC keyword.
Syntax
Example SELECT * FROM Persons WHERE age > 20 ORDER BY name ASC 3.7.1 Order by Two Columns It is also possible to order by more than one column. When ordering by more than one column, the second column is only used if the values in the first column are equal: SELECT column_name(s) FROM table_name ORDER BY column1, column2
Example SELECT * FROM Persons WHERE age > 20 ORDER BY name,address ASC
3.8 Update Data In a Database The UPDATE statement is used to update existing records in a table. Syntax UPDATE table_name SET columnl=value, column2=value2,... WHERE some_column=some_value Note: Notice the WHERE clause in the UPDATE syntax. The WHERE clause specifies which record or records that should be updated. If you omit the WHERE clause, all records will be updated! Example UPDATE Persons SET address='Segamat', age=20 WHERE name='Ahmad'
3.9 Delete Data In a Database The DELETE FROM statement is used to delete records from a database table. Syntax DELETE FROM table_name WHERE some_column = some_value 10
Note: Notice the WHERE clause in the DELETE syntax. The WHERE clause specifies which record or records that should be deleted. If you omit the WHERE clause, all records will be deleted! Example
1%3
buang (1) calendar (1) cdcol (1) cjalan (34) cjportal (78) dbspa (27) dmyreports (1) elearning1 (93) information_schema (28) kawen (88) mysql (23) phpmyadmin (8) test (2) lestexam (15) webauth (I)
MySOL
)k.1 Server localhost na TCPAP
Es]
JS
Geesel
User. rooi@docalhost
121
Interface
Language s), English Theme / Style. Original
Web server
e Apache/2.2 11 (Win32) DAVI2 modssV2.2.11 OperiSSU0.9.81 mod_autoindes color PHP5. 2.8 I MySOL client version: 5.1 30
1 PHP extension: aqui'
e Custom color:
6.1 Reset
phpMyAdmin
O
a) Database in your web server b) Information about web server
L.:I
Documentation
Wiki Homepage (ChangeLog) (Subversion) (Lists)
php
11
Insert database name dbStudent and click create and you will see dbStudent displayed on your left-hand frame in phpMyAdmin.
4.2 Creating a table in your database
The left-hand frame in phpMyAdmin is used for navigation. Click on your database the navigation frame and a new window will appear on the right hand side.
Server locallost 1 iy Database: dbStudent
I I I
Database (Databases) dbStudent
(.1'311410rue X Di op
zsoL ,
(o)
Name
Number of fields
We will create a table in the database, called "lecturer". Use the Create new table feature. Type in the name of the new table into the Name: lecturer, and the number of columns in the table (4) into Fields:. This tutorial is only designed to show you the basic php/MySQL/phpMyAdmin functions. You can delete it using the Drop function. You will want to allow for growth in your table.
stitictui
asg SOL
Import
Xprop No tables found in database. eate new table on database Astudent Name: lecturer Number of fields: 4
Click Go and you should see something like this. The table title now appears with under the database name. 12
trill Table:
iCCIIIIel
Type 0
IlefanIt 2
Co llatioa
'id
INT
name
VARCHAR
s^
20
None
address
VARCHAR
50
None
age
111T
None
Table comments:
Collation:
PARTITION rletiriltion: CJ
say
?I OrAdd 1
field(s) [Go j
Now enter the names and attributes of our table fields. Enter the following information as above: 1Field
!
Length 11 20 -
AI Yes
Id Name
address i--age
50 3
The Length value indicates the maximum allowable length of characters for input. There are many different values that can be set for Type. The Types specified in this example aren't the most efficient, but just used for the purposes of this exercise. The "id" field, which will be used as a Primary key for this table, has been set to auto_increment, saving you from having to having to type in the next number in sequence when you input records. Once you've entered all the values, click Save. A screen like this will appear.
13
iddr eu
aq<
) =GINS MISR(
Field u u
u
Type int(11)
Collation
Extra auto_increment =i
Action
id Hanle
varchar(20) latinl_swedish_ci
[ji? X RV I.0 IF
X k2
X
7:7'4
51
X
After id
5i-.E Add 1
field(s)
, I Go
a) SQL statement b) Action : Browse the data Edit or change table structure
X El
Delete field Set primary key Set unique Index Full Text
Congratulations!-You have created your table! The corresponding SQL command for creating these fields is also displayed. This isn't needed but in time you will start to recognise MySql commands Note that you can use Drop to delete a table or fields.
14
4.3 Inputting data into the table. Click the tab labeled "Insert" - and another window should appear, like this.
NB' owse Field id Type int(11) v Ahmad Taman Kemawan v 21 (Kull e S SOL , Seatch Function Null fl Expoit Impoit ROperation Value
Now type in the details for each of the fields for this record. The "id" column was set to automatically increment so you do not need to enter a number. Note - if you ever get lost with phpMyAdmin navigation click "Home" in the left hand nav bar and start again. Now click Save and the record is saved to the lecturer table. The previous window reappears with the SQL command for the insert. You can keep adding recordsby re-selecting Insert". For multiple records, you can select the "Insert another new row" radio button on the input form. When you've finished entering several records into the table, you can check them by clicking on the Browse tab. You can click on individual records for editing or deleting. 4.4 Browse data for each table Click the tab labeled "Browse" to view all record in table.
al-1 131 "wse Stiucime in SOL , Sealch ;Eifiseit [mExpoit minivan
L1HI T 0 , 00
[11 Profiling
30
row(s) starting from record # 0 mode and repeat headers after 100 cells
name
a s I s liess
age 18 28
X.
E.
cells
row(s) starting from record # 0 mode and repeat headers after 100
15
4.5 SQL
We can use phpMyAdmin's Structure sub-page in Database view, or we can use the SQL query box to enter the appropriate statement:
Browse
Search 5.dnseit[Export
r impou
RO I ) ei
Bookmark this SQL query: [ Delimiter Show this query here again
u R
4.6 Search
Click the tab labeled "Search" to find record in your table. Put some value into related field and click go to make a searching.
.;;Blowse [:!_r.
Smuctilie ,0 SOL Sealcit z.Elusert ISExpott Import ;Operations `'Empty X Diop
Do .1 "query by example iwildt..11.1. Field id name Type int(11) varchar(20) latinl_swedish_ci LIKE LIKE . Collation Operator ,... v v ... Value
age
+ Options
int(3)
Go
16
- Click on your database name in the left hand navigation bar - Click on EXPORT (top tab) - Highlight the table/s you want to back up and choose SQL - Select STRUCTURE and DATA radio button - Select "Enclose table and field names with backquotes" - Select "Save as file" and "zipped" check boxes - Click "Go" and a zipped archive file will be generated.
Snndw e
,r4 SOL
Search LOOrieiy
- View dump (schema) of ilatahasr Exploit Select All I Unselect All Options
ectur0
Comments
Ei Enclose export in a transaction u Disable foreign key checks
SOL compatibility mode NONE
O
CodeGen
CSV CSV for MS Excel Microsoft Excel 2000
- O StiuLtioe
If you want to insert your table or database in web server, click the tab labeled "Import" and browse you file. Usually we use SQL file to generate the record.
[5 Sri acne e ,C7 SOL -File to inipoi Location of the text file Character set of the file: AB Imported file compression will be automatically detected from None, gzip, zip Partial i1111,01i I Browse, I (Max . 65,536 haB) Search Xri Exton nir 'introit i' i' r;Designer ROperations sm Privileges X, Di op
E Allow the interruption of an import in case the script detects it is close to the PHP timeout limit- This might be good way to import large files, however it can break transactions.
Number of records (queries) to skip from start 0
-Format of fin roiled file ) DocSQL Opti
:, SOL
NONE
Go
17
4.8 Privileges
MySQL provides privileges that apply in different contexts and at different levels of operation: Administrative privileges enable users to manage operation of the MySQL server. Database privileges apply to a database and to all objects within it. These privileges can be granted for specific databases, or globally so that they apply to all databases. Privileges for database objects such as tables, indexes, views, and stored routines can be granted for specific objects within a database, for all objects of a given type within a database
LOClatallases
,n SOL
Status
:9 Variables
Host: Use text field: Password: Use text field: Re-type: Generate Password: IL. Generate 11 Copy
-Database for riser None Create database with same name and grant all privileges .::) Grant all privileges on wildcard name (username12/0) 1;1011.11 pi ivileges tCheck All l_litcheck All)
Note; AdySOL psi wite9e names are expressed in English
-Data
u u u u u SELECT INSERT UPDATE DELETE FILE
Structure
u u u u u CREATE ALTER INDEX DROP
Ad irrinistartio
u u u u u GRANT
Resource
Note:Setitat
MAX UPDA7
MAX CONNI
References :
http://www.mysql.com/
18
Exercise:
You are given a task to develop complaint management system for ICT department. Based on the following information develop database named ' dbComplainrusing MySQL.
complaintlD
complaints
19
Code :
<?php
//connection to mySQL
$host="localhost"; $username="root"; $password=""; $link = mysql_connect(Shost,$username,$password)or die("Could not connect");
Connect.php
MENU
add
view
Code :
<html> <head> <title>Menu</title> </head> <body> <p>MENU</p> <p><a href="addform.html">add</a></p> <A><a hrr="yjew.php">view </a></p>
> 4 </ solory4 "' I- 2
" C9-41r h
th
> reo' Ch
</html> menu.html
Code :
<form action="add.php" method="post"> <table width="212" border="1" bordercolor="#000000"> <tr> <td width="75"><strong>NAME</strong></td> <td width="121"> <input name="txtName" type="text" ></td> </tr> <tr> <td><strong>ADDRESS</strong></td> <td> <input nanne="txtAddress" type="text" ></td> </tr> <tr> <td><strong>TEL</strong></td> <td> <input name="txtTel" type="text" ></td> </tr> <tr> <td colspan="2"><div align="center"> <input type="submit" name="Submit" value="Submit"> </div></td> </tr> </table>
e
114eRttitrn't
0,
da-Cevm . kt '
4
Code :
<?php include 'db_connect.php';
//insert data
$result = mysql_query("INSERT INTO tblPembekal(name,address,tel) VALUES ( 1 $add_name','$add_addressl,'$add_ter)" );
add.php
4) View Data
back to Menu 12 11 =mar lezarn s e Ramat 1517 082131233 078762812 edit edit
delete delete
Code :
<?php
//Connection to database
include 'db_connect.php'; $result = mysql_query("Select * from tblPembekal order by name Asc",$link) or die("Database
Error"); ?> <p>back to <a href="menu.html">Menu</a></p> <table width="493" border="1">
<?php
//data looping
while($row = mysql_fetch_array($result, MYSQL_BOTH)){ ?> <tr> <td><?php echo $rowric11;?></td> <td><?php echo $row[Inamel;?></td> <td><?php echo $rowraddressT,?></td> <td><?php echo $row['tel'];?></td> <td><div align="center"><a href="view_edit.php?user_id=<?php print ($rowrid1);?>">edit</a></div></td> <td><div align="center"><a href="delete.php?user_id=<?php print ($row['id']);?>">delete </a></div></td> </tr>
41 i
Code :
<form action="edit.php" method="post"> <?php include 'db_connect.php';
//view selected id
Sedit_id=$_GET['user_idl]; $result = mysql_query("SELECT * FROM tblPembekal WHERE id='$edit_ic" );
?
>
<table width="212" border="1"> <?php while ( $user = mysql_fetch_array( $result )) $id=$user['id']; $name=$user['name']; $address= $user['address']; $tel= $userftell; ?> <tr> <td width="75"><strong>ID</strong></td> <td width="121"> <input name="txtld" type="text" value="<?php echo $id ?>"></td> </tr> <tr> <td><strong>NAM E</strong></td> <td> <input name="txtName" type="text" value="<?php echo $name ?>"></td> </tr> <tr> <td><strong>ADDRESS</strong></td> <td> <input name="txtAddress" type="text" value="<?php echo $address ?>"></td> </tr> <tr> <td><strong>TEL</strong></td> <td> <input name="txtTel" type="text" value="<?php echo $tel ?>"></td> </tr> <tr> <td colspan="2"><div align="center"> <input type="submit" name="Submit" value="Submit"> </div></td> </tr> </table> </form> view_edit.php
5) Delete data
Code : <?php include 'db_connect.php'; //delete data $delete_id=$_GETruser_in $result = mysql_query("DELETE FROM tblPembekal WHERE id='$delete_id" ); if ($result) echo " Delete Successfully ! <a href='view.php'> back to view </a>"; else echo "Problem occured !"; ?> edit.php
6) Search form
txtSearch
I Search
Code : <form name="forml" method="post" action="search_action.php"> <input name="txtSearch" type="text" id="txtSearch"> <input type="submit" name="Submit" value="Search"> </form> search.php
Code :
<?php //Connection to database include 'db_connect.php'; $search=S_REQUEST["txtSearch"]; $result = mysql_query("Select * from tblPembekal WHERE name LIKE '$search' order by name Asc",Slink) or die("Database Error"); ?>
<td><?php echo $row['id'];?></td> <td><?php echo Srow[Inamel?></td> <td><?php echo $row['address'];?></td> <td><?php echo $row['tel'];?></td> </tr>
<?php }?> // close loop
</table> Search_action.php
z cn
O
CL -C 0-
PHP Application
C
O
0
.E 0 C I 0
ro
(1.) 0
-c V
(1) 0. 0 -0
ay
03
CO
V;
CD v.)
a.) _c A
A
-
-C
o.
0.
C
. 61)
_c
..
0 .-1 c.) a,
ii C 0
0 ..) o ro 0_ 0 Z < cu
E MS
4., VI 0 a. =i i
6 2
E t,
e
n
.
0
..0
a,
E
=
0
...,
A 7.
.0 ' 11 '' 0.1 CL Z.,
C
E
773 ._ QJ 4: CU r -C CI) e i
..
,Z .1... n;
E
8
-.-x
..I..
c on
o
/ 11
a, 1.
II 0) a
. A
..,, ra
.
a
0.J
11
To = Y `,,-. 1: , a ,--
0 a) i""
C
l i = a
E
a.,
8 a a_ -c H CL
V
-5-.
r).
a
s- -H V ro
.. 0- 37
= II
7 -0 . = v, Ec ,_ o
PHP Application 7) Log in Form
0 2 -II 6.. CU
-o ,,_ a.
L .) II 4)
-,L7
0 I I
a, ,17.1.
-z.-.. o ..,)
iro
o
C
LI o
c 11-
03 u CL
'E D CU E .o cn v ro `.'\' 0 C A
E _ca
0. 6
C1) C
C A > .I-. I-' I-= A. 4 - I T1 11 0 1:2 7 , z _c!) a, u. m 0. -0 0ro _o 0. E ... , c *.= re c ro 0 .L-.
m v 70
-o U .E.
o a- -0 _c = -
v) v)
7 V -\:" , V V v 7 A E
V
_a co -to ;) vc i
1-0 Tr,>. E
0 2
.7co c.., o
0zo
1.--a,
o. ' r. 0 '
V
,., ..
.-.-.
.c F,
checkLogin. php
7 1./1. - .
UiTM
2011
BASIC DREAMWEAVER
A. Default interface
tr.
So.
. ite
B. Define Site 1. Click 'Define a site' -4 enter your name site Click Next
Site Definition tot awns
,
iii
Preso
Advanced
Site Definition
Editing Hes Testrg Files glaring Wes
A tile. in Matiornedta Diearnereavei W. n a CONed. d her and toidei: that conetoondt io a websee on a :ewer
Ezetole. MySite
UiTM
2011
click Next
I
Panic
Advanced
Site Definition
albs ' g fiks, Part 2 Testing Pies Sharing Fats
Do you want to work with a seivet technology such as ColdFu 1 ASP NET, ASP. JSP PHP? No.! do not wart to use a :elver technology 0 yes, I wart to use a serve, technology.
'I
Ned..
Carve)
Help
3.
Choose 'Edit and test locally' -> Select your folder in root folder
(Note : Normally in C:Ixampphtdocs\ or c:\inetpub\wwwroot\ )
'
Site Definition
&Siting like, Part 3 Tooting Fks Sharhg Fins
Hair do you went to work with you get gang development? a Edit and tett boaly ley toning serve, is on gar cernauteg Edit loceilsk than upload to wrote testing save Edo 4iecdy on mode testing seised using lord network Edit dimension remote testing server using FTP or PDS
UiTM
2011
4.
Enter URL
(Note :http://localhost/RootFolder OR http://127.0.0.1/RootFolder )
Site Definition for aims
EWA
Advanced .
Site Definition
EdamF Testing Files, Past 2 SharingHes
a blowteri to I needt
lest URL ._
'.
fad.
Nora a
Cancel
Help
5.
6.. Advanced
Site Definition
63tesg Nes Ttstrtg Nes Sharing Hes
When you are done !del a lie. do tow tcpy i to another machine , This raigff be the esoduction
web sewer a a sla9ng server that you shore web learn members. teal...want to use elevate serve? N9
'lack
Nq> ,
UiTM
2011
Site Definition
biting hies Testre Nes Sharing hies, Part 2.
DAorcaectNedlIS syeterd
Pefreth Remote Pk Lot Avtoolaboali
ask
Nee>
Hek,
7.
Choose 'No'
click Next
Site Definition for aims
Bask
Advanced
Site Definition
Exiting Files Testing Files Skating Vries, Part 3
*IP
Nee
Celled
H*
UiTM
2011
8.
Finish
Site Definition
Summary You vie has the lollossmg settings Local Into Ske Name aina Local Rool Takla CAsampicattdocs \ aims \ Remote Info: Access'. local/Nelwak Remote Fokirs D Miojer,t/AIMS/symern Check.inicheck-mit Disabled Testing Server. ACre,t Local/Nei...A Runde Tokio C VaifitscAlvdoctlerns You see can be !Whet configued ming the Advanced Tab
<11 ,4,
Q on
el
Help
TENTATIF PROGRAM
: Bengkel Explorasi PHP dan MySQL : 28-29 JANUAR! 2012 : MAKMAL KOMPUTER SL, UiTM KAMPUS SEGAMAT
Tallith
8.00 pagi 8.30 pagi SABTU
Masa
AktIvIti Pendaftaran MySQL Basic - Intro - CREATE database, table INSERT and SELECT Rehat MySQL Basic(samb) Update and DELETE - phpMyAdmin Rehat & Solat PHP Editor - WYSIWYG editor PHP Basic - Intro - PHP Syntax, Operator & conditional statement. PHP Basic (samb) - Looping - Function Bersurai Pendaftaran PHP Basic (samb) - Form handling - Session and cookies Rehat PHP Applica t ion on - Simple Menu, add and view data. Rehat 8, Solat PHP Application(samb) - Delete and search - Project / Tips
.
2.00 ptg
5.00 ptq 8.00 pagi 8.30 pagi 10.00 pagi 10.30 pagi 29 Jan 2012 12.30 tgh 2.00 ptg 5.00 ptq
Bersurai