Home >Documents >Basic PHP MySQL

Basic PHP MySQL

Date post:04-Jan-2016
Category:
View:51 times
Download:4 times
Share this document with a friend
Description:
IT, PHP MYADMIN TUTORIAL
Transcript:
  • php) Quick Start: PHP for Beginner

    Module Prepared by : Mohd Lezam Lehat (Bsc.Comp, Msc.IT)

  • Prepared by Mohd Lezam Lehat

    Table of Contents

    Item Page

    1. Introduction 3

    2. Basic PHP Syntax 3

    3. PHP Operators 7

    4. Conditional statement 8

    5. Looping 10

    6. PHP Functions 13

    7. PHP Form Handling 16

    8. The $ GET Variable 17

    9. The $ POST Variable 18

    10. The $ REQUEST Variable 18

    11. PHP Sessions 19

    12. PHP Cookies 20

    13. Tutorial 21

    2

  • Prepared by Alohd Lezam Lehat

    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

    2. Basic PHP Syntax

    A PHP scripting block always starts with . A PHP scripting block can be placed anywhere in the document.

    On servers with shorthand support enabled you can start a scripting block with .

    However, for maximum compatibility, we recommend that you use the standard form (

  • Prepared by Mohd Lezam Lehat

    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.

    '

    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:

    4

  • Prepared by Mohd Lezam Lehat

    2.3 PHP is a Loosely Typed Language

    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)

    2.5 Strings in PHP

    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.

    5

  • Prepared by Mohd Lezam Lehat

    2.6 The Concatenation Operator

    There is only one string operator in PHP.

    The concatenation operator (.) is used to put two string values together.

    To concatenate two variables together, use the dot (.) operator:

    The output of the code above will be:

    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.

    2.7 Using the strlen() function

    The strlen() function is used to find the length of a string.

    Let's find the length of our string "Hello world!":

    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

  • Prepared by Mohd Lezam Lehat

    Let's see if we can find the string "world" in our string:

    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 Result + 'Addition x=2

    x+2 4

    _J ' - Subtraction

    i x=2 5-x

    3

    * I Multiplication I i

    x=4 x*5

    20

    Division 15/5 3 I 5/2 2.5

    oh) Modulus (division remainder) 5%2 -71

    10%8 2 . .

    ; 10%2 0 ++ ;Increment x=5

    x++ x=6

    -- 1Decrement I

    x=5 x--

    x=4

    3.2 Assignment Operators

    'Operator ,.

    Example Is The Same As

    ,

    x=y 7X=y +=

    -=

    x+=y ixx-Fy fx=x-y x-=y

    I*= Ix*=y x=x*y V= ix/=y x=x/y

    7

  • Prepared by Mohd Lezam Lehat

    Oh = x%=y x=x%y

    3.3 Comparison Operators

    Operator Description 'Example jis equal to

    != is not equal is greater than is less than

    >= is greater than or equal to 8 returns false 5=8 returns false 5 1) returns true or

    x=6 Y= 3

    (x==5 I I y==5) returns false not

    x=6 Y= 3

    !(x= =y) returns true

    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!":

    8

  • Prepared by Mohd Lezam Lehat

    i 1

    If more than one line should be executed if a condition is true/false, the lines should be enclosed within curly braces:

    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!":

    9

  • Prepared by Mohd Lezam Lehat

    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

  • Prepared by Alohd Lezatri Lehat

    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

    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:

  • Prepared by Mohd Lezam Lehat

    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:

  • Prepared by Mohd Lezam Lehat

    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 !

  • Prepared by Mohd Lezam Lehat

    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:

  • Prepared by Mohd Lezam Lehat

    ,

    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.

    The output of the code above will be:

    1 + 16 = 17

    15

  • Prepared by Mohd Lezam Lehat

    7. PHP Form Handling

    The most important thing to notice when dealing with HTML forms and PHP is that any form element in an HTML page will automatically be available to your PHP scripts.

    Form example:

    Name:

    , Age: '

    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:

    Welcome . You are years old.

    J

    A sample output of the above script may be:

    Welcome John. You are 28 years old.

    16

  • Prepared by Mohd Lezam Lehat

    8. The $_GET Variable The $_GET variable is an array of variable names and values sent by the HTTP GET method.

    The $_GET variable is used to collect values from a form with method="get". Information sent from a form with the GET method is visible to everyone (it will be displayed in the browser's address bar) and it has limits on the amount of information to send (max. 100 characters).

    Example

    Name: lAge: ' I

    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 . You are 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

  • Prepared by Mohd Lezam Lehat

    9. The $_POST Variable The $_POST variable is an array of variable names and values sent by the HTTP POST method.The $_POST variable is used to collect values from a form with method="post". Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send.

    Example ,Enter your name: Enter your age:

    When the user clicks the "Submit" button, the URL will not contain any form data, and will look something like this:

    http://www.centre2u.com/welcome.php

    The "welcome.php" file can now use the $_POST variable to catch the form data (notice that the names of the form fields will automatically be the ID keys in the $_POST array):

    Welcome . You are years old!

    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.

    10. The $_REQUEST Variable The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE.

    The PHP $_REQUEST variable can be used to get the result from form data sent with both the GET and POST methods.

    Example Welcome . You are years old!

    18

  • Prepared by Mohd Lezam Lehat

    11. PHP Sessions

    A PHP session variable is used to store information about, or change settings for a user session. Session variables hold information about one single user, and are available to all pages in one application.

    11.1 Starting a PHP Session

    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 tag:

    1

    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:

  • Prepared by Mohd Lezam Lehat

    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:

    You can also completely destroy the session by calling the session_destroy() function:

  • Prepared by Mohd Lezam Lehat

    Syntax setcookie(name, value, expire, path, domain);

    Example 1

    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:

    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.

    In the example above the expiration time is set to a month (60 sec * 60 min * 60 hours * 30 days).

    12.2 How to Retrieve a Cookie Value?

    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:

    21

  • Prepared by Mohd Lezam Lehat

    In the following example we use the isset() function to find out if a cookie has been set:

  • 2. Ope

    a) ,

    Prepared by Mohd Lezam Lehat

    13. Tutorial 1. Basic Coding

    a) la.php

    b)1'

  • Prepared by Mohd Lezam Lehat

    3. Conditional Statement / Looping

    a) 3a.php

    Today is :

    b) 3b.php

    24

  • Prepared by Mohd Lezam Lehat

    4. Function

    a) 4a.php

    a) 4a.php

    25

  • Name: Gender:

    Male Female

    Name: Gender :

    5. Form

    a) 5a.php

    26

    Prepared by Mohd Lezam Lehat

  • Prepared by Mohd Lezam Lehat

    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

    staffID

    DATE

    STAFF ID

    detail DETAIL

    LOCATION

    CATEGORY Choose Category

    Submit

    location

    category

    Action: User sent complaints (tips:Add) B. Head Of Department i) View and assign complaint

    ID DATE COMPLAINT PERSON IN STATUS ACTION

    1 01 102/2012 software installation. Choose Category Pending Submit 1 2 02402/2012 vines Ahmad Success

    1 01/012 1 sot ware installation Choose Category Y Pending Submit

    ii)View complaint details

    List Only Staff from IT

    Action: set personiD, dateassign,status (tips:update)

    DATE 12102.' 2012 STAFF II) Ahmed

    DETAIL Please install MS Office LOCATION A101 CATEGORY Software

  • fd,

    Mg

    Quick Start: MySQL for Beginner Module Prepared by : Mohd Lezam Lehat (Bsc.Comp, Msc.IT)

  • Prepared by Mohd Lezam Lehat

    TABLE OF CONTENT

    MySQL for Beginner

    1. Introduction 3

    2. Installation 4

    3. SQL statement 6

    - Connect 6

    - Create 6

    - Insert 8

    - Select 9

    - Where 9

    - Order By 9

    - Update 10

    - Delete 10

    4. Getting Started With phpMyAdmin 11

    2

  • Prepared by Mohd Lezam Lehat

    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".

    1.1 Database Tables

    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":

    r----- LastName (FirstName Address City Hansen , la itimoteivn 10 :Sandnes Svendson Move Borgvn 23 Sandnes Pettersen IR;

    a r i Storgt 20 ;Stavanger

    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 Hansen Svendson Pettersen

    1.3 Download MySQL Database

    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

    3

  • Prepared by Mohd Lezam Lehat

    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 mysql-essential-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-noinstall-5.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.

    4

  • Prepared by Mohd Lezam Lehat

    Dov..nk ad NISI

    Run \ISI

    l\ lyS (} 1..

    Regislci

    Run AlrSQL

    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

    Figure 2.2. Installation Workflow for Windows using Zip

    2.2 Installation on different Operating system

    For more information about installation MySQL : http://dev.mysql.com/doc/refman/5.1/en/installing.html

    5

  • Prepared by Mohd Lezam Lehat

    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.

    3.1 Create a Connection to a MySQL Database

    Before you can access data in a database, you must create a connection to the database.

    In PHP, this is done with the mysql_connect() function.

    Syntax mysql_connect(servername,username,password);

    Parameter Description I servername

    Optional. Specifies the server to connect to. Default value is "localhost:3306"

    Username Optional. Specifies the username to log in with. Default value is the name of the user that owns the server process

    Password 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.

    3.2 Create a Database

    The CREATE DATABASE statement is used to create a database in MySQL.

    Syntax CREATE DATABASE database_name

    Example CREATE DATABASE dBase

    6

  • Prepared by Mohd Lezam Lehat

    3.3 Create a Table

    The CREATE TABLE statement is used to create a table in MySQL.

    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)

    3.3.1 Data types

    TINYINT A very small integer. The signed range is -128 to 127.

    SMALLINT - A small integer. The signed range is -32768 to 32767.

    MEDIUMINT - A medium-size integer. The signed range is -8388608 to 8388607.

    INT - A normal-size integer. The signed range is -2147483648 to 2147483647.

    BIGINT A very large integer.

    Some other less common number options include:

    FLOAT- A floating-point number.

    DOUBLE A double-precision floating-point number.

    DECIMAL - A packed exact fixed-point number.

    If the field is to be used to store text or both text and numbers combined, here are some choices:

    VARCHAR is for varying characters and can be up to 255 characters in length.

    TEXT is a column with a maximum length of 65,535 characters easy to search.

    BLOB is a column with a maximum length of 65,535 characters case-sensitive.

    If the field is to be used to store dates, here are some choices:

    7

  • Prepared by Alohd Lezam Lehat

    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,...)

    8

  • Prepared by Mohd Lezam Lehat

    Example

    INSERT INTO Persons (name, address, age) VALUES ('Ahmad', rJementah', 1 35 1 )");

    3.5 Select Data From a Database Table

    The SELECT statement is used to select data from a database.

    Syntax SELECT col um n_na me(s) FROM table_name

    Example

    The following example selects all the data stored in the "Persons" table (The * character selects all the data in the table):

    SELECT * FROM Persons

    3.6 The WHERE clause

    The WHERE clause is used to extract only those records that fulfill a specified criterion.

    Syntax SELECT column_name(s) FROM table_name WHERE column_name operator value

    Example

    SELECT * FROM Persons WHERE age > 20

    3.7 The ORDER BY Keyword

    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 SELECT column_name(s) FROM table_name ORDER BY column_name(s) ASCIDESC

    9

  • Prepared by Mohd Lezam Lehat

    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

  • Q pttp)16;pticif.r2

    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)

    Please select a database

    O

    MySOL localhost

    0 Collation

    Es] MySOL connection collation: ulte_genexed_ci tte Geesel v

    tx:, Create new database

    Interface

    Language s), English JS Theme / Style. Original

    e Custom color: 6.1 Reset I

    e Font size: 825. ttt

    Prepared by Mohd Lezam Lehat

    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 DELETE FROM Person WHERE age > 60

    4. Getting Started With phpMyAdmin

    Once you log in, a phpMyAdmin screen appears as shown below.

    gt.1 Server: lucalliost

    ,t,isDatabases SOL 1) Sirius DV:id:doles rfflCIntusets Eel Engines :)Privileges SPrucesses at/Export

    Actions MySOL

    )k.1 Server localhost na TCPAP

    ij Server version. 5.1 30-community e Protocol version 10

    User. [email protected] 121

    MySOL charset UTF-8 Unice& (ull8)

    Web server

    e Apache/2.2 11 (Win32) DAVI2 modssV2.2.11 OperiSSU0.9.81 mod_autoindes color PHP5. 2.8 MySOL client version: 5.1 30

    1 PHP extension: aqui'

    phpMyAdmin

    Version information: 3.1.1 L.:I Documentation

    Wiki

    Homepage (ChangeLog) (Subversion) (Lists)

    php

    a) Database in your web server b) Information about web server

    11

  • Prepared by Mohd Lezam Lehat

    4.1 Creating a new database

    Actions

    MySQL localhost

    Cleate new database 0 dbStudent Collation v Create

    MySQL connection collation: utfa_general_ci v C)

    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 (.1'311410rue X Di op zsoL , Search LOC/troy til--.1Export & ltn

    Database (Databases)

    dbStudent (o) No tables found in database.

    No tables found in database

    new talrl. "it .lataltae dbStudent

    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 e asg SOL Sealch, 14110nery ,IrrExport 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

  • Prepared by Mohd Lezam Lehat

    J Server: localliest It ,:,6A Database: illostinlent n trill Table: iCCIIIIel Flelil Type 0 LengtIrVallies'

    IlefanIt2

    Co llatioa

    'id INT " 11 None

    name VARCHAR s^ 20 None

    address VARCHAR 50 None

    age 111T 3 None

    Table comments: Storage Engine: 0

    Collation:

    MyISAM

    PARTITION rletiriltion: CJ

    field(s) [Go j

    say?I OrAdd 1

    Now enter the names and attributes of our table fields. Enter the following information as above:

    1Field Type Length Index AI ! Id int 11 Primary key Yes l Name char 20

    - T address char 50

    i--- age char 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

  • Prepared by Mohd Lezam Lehat

    -, Table 'dbStudenT.'lecturer i has been created. =ATE TOLE ' (114 d c 'lento (

    ', ( ll. I NOT NU11 AUTO I 11003101NT PRINIUZY , 'nx.e ( )HOT RULE , iddreu ( 0 ) NOT NULL , aq< I NOT 11101.

    ) =GINS MISR(

    [ Edit J [ Create PHP Code

    Field Type Collation Attributes Null Default Extra Action

    q id int(11) No None auto_increment [ji? q Hanle varchar(20) latinl_swedish_ci No None =i X RV I.0 IF

    q address int(50) No None X k2 q age nt(3) No None X

    t Check All / Uncheck All With selected 51 X 7:7'4

    Print view 4 Relation view c Propose table structure CJ 5i-.E Add 1

    field(s) At End of Table At Beginning of Table After id , I Go

    a) SQL statement b) Action :

    Browse the data

    Edit or change table structure

    X Delete field

    El 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

  • Prepared by Mohd Lezam Lehat

    4.3 Inputting data into the table.

    Click the tab labeled "Insert" - and another window should appear, like this.

    NB' owse (Kull e S SOL , Seatch fl Expoit Impoit ROperation

    Field Type Function Null Value

    id int(11)

    name varchar(20) v Ahmad

    address varchar(50) Taman Kemawan

    age int(3) v 21

    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 Showing rows 0

    - 1 (2 total, Query took 0.0004 sec) SELECT EWE 1-acvL1HI T 0 , 00

    [11 Profiling

    Show 30 row(s) starting from record # 0 in horizontal mode and repeat headers after 100

    cells Sort by key: N on e + Options

    iJ name a n I n liess age X 3 Mohd Lezam Lehat Taman Kernawan

    18 X 4 Ahrnad Jementah 28

    L Check All / Uncheck All With selected X. E.

    I Show: 30 row(s) starting from record # 0 in horizontal mode and repeat headers after 100

    cells

    15

  • Prepared by Mohd Lezam Lehat

    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 6 Stiuctui e sk7 SOL Search 5.dnseit[Export r impou RO I) ei

    Rim SOL finely pieties on database (lbstudent:

    Bookmark this SQL query: q Let every user access this bookmark q R

    [ Delimiter Show this query here again

    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.

    [:!_r..;;Blowse Smuctilie ,0 SOL Sealcit z.Elusert ISExpott Import ;Operations `'Empty X Diop

    Do .1 "query by example iwildt..11.1.

    Field Type Collation Operator

    Value

    id int(11) ,...

    name varchar(20) latinl_swedish_ci LIKE v

    address varchar(50) latinl_swedish_ci LIKE

    v

    age int(3) . ...

    + Options

    Go

    16

  • Prepared by Mohd Lezam Lehat

    4.7 Backup your data

    - 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 Imp oil utDesignei p. Op e ations ^Privileges X Drop - View dump (schema) of ilatahasr

    Exploit Options

    Select All I Unselect All ectur0

    q Disable foreign key checks SOL compatibility mode

    NONE O

    - O StiuLtioe CodeGen DA.dd DROP TABLE / VIEW / PROCEDURE / FUNCTION / EVENT

    CSV ['Add IF NOT EXISTS Er

    AUTO_INCREMENT value CSV for MS Excel q Enclose table and field names with backquotes

    Microsoft Excel 2000 q Add CREATE PROCEDURE / FUNCTION / EVENT

    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

    Search Xri Exton nir 'introit 'i'ir;Designer ROperations sm Privileges X, Di op

    -File to inipoi

    Location of the text file I Browse, I (Max . 65,536 haB)

    Character set of the file: AB Imported file compression will be automatically detected from None, gzip, zip

    Partial i1111,01i 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 [SOL compatibility mode

    NONE

    Go

    Add custom comment into header (In splits lines) Comments

    Ei Enclose export in a transaction

    17

  • -Login Information

    User name Use text field .

    Host: Use text field:

    Password: Use text field:

    Re-type:

    Generate Password: IL. Generate 11 Copy

    Prepared by Mohd Lezam Lehat

    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 1.1! Chaisets 65E11(.011es

    Add a new User

    -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

    Ad irrinistartio Resource -Data Structure

    q SELECT q CREATE q GRANT Note:Setitat q INSERT q ALTER q SUPER

    q UPDATE q INDEX q PROCESS MAX QUER:

    q DELETE q DROP q RELOAD MAX UPDA7

    q FILE q CREATE TEMPORARY TABLES q SHUTDOWN MAX CONNI ri cunm 77TVW runm nftrhoncec

    References :

    http://www.mysql.com/

    18

  • complaints

    C complaintlD

    Prepared by Mohd Lezam Lehat

    Exercise:

    You are given a task to develop complaint management system for ICT department. Based on the following information develop database named ' dbComplainrusing MySQL.

    a)Staff(staffID,name,room,department) b)Complaints (complaintID,staffID,data,detail,category,location) c)Executants(executeID,complaintID, adminlD, status, dateAssign, dateComplete) d)Admin(adminID,staffID,level,usernanne,password)

    19

  • Tutorial: PHP application Module Prepared by : Mohd Lezam Lehat (Bsc.Comp, Msc.IT)

  • Prepared by Mohd Lezam Lehat

    1) Create database connection :

    Type of Database connection :

    a)mysql_connect - connect duration the script access the db.

    b) mysql_pconnect - persistence connection - only call int once for the session

    c)mssql_connect - MSSQL server

    d) PHP data Objects (PDO) - PHP 5.1 -access multiple database(Informix,Oracle,ODBC,DB2,MSSQL, Sybase, PostgresSQL etc)

    Code :

  • Menu

    MENU add view

    4 "' I- 2 " C9-41r h th > reo' Ch

    txtN am e

    txtAddress

    txtTel

    NAME 1

    ADDRESS

    TEL

    Submit I

    Prepared by Alohd Lezam Lehat

    Code :

    menu.html

    3) Create form to add data

    Code :

    NAME

    ADDRESS

    TEL

    e

    114eRttitrn't 0, da-Cevm .kt '

    4

  • Prepared by Mohd Lezam Lehat

    3.1) Action for add data

    Code :

  • Prepared by Mohd Lezam Lehat

    Code :

    back to Menu

  • Prepared by Mohd Lezam Lehat

    Code :

  • Prepared by Mohd Lezam Lehat

    4.2) Action for edit data

    Code :

  • Prepared by Mohd Lezam Lehat

    6) Search form

    txtSearch I Search

    Code :

    search.php

    6.1) Action for search data

    back to Menu

    12 ammar segamat 082131233

    Code :

  • Pre

    pare

    d by

    Moh

    d Le

    zam

    Leh

    at

    PHP

    App

    licat

    ion

    O

    03

    t

    C I 0 0

    (1.) C

    0. 0 -c ay

    V; CD V v.)

    CL -C 0-

    .E 0 C

    ro

    0

    (1)-0

    CO a.)

    _c A

    z O cn O

    Pre

    pare

    d by

    Moh

    d Le

    zam

    Leh

    at

    PHP

    App

    licat

    ion

    7) Lo

    gin

    Form

    A

    -o. -C 0. C

    . 61) 0

    .-1 c.) a, _c U

    i i C 0

    ..E MS

    4., VI

    0 a.

    =i i 0

    ..0 a, E e A 0 7.

    = n ...,

    E E -.-- .0 8 x a,

    ..,,

    ra ..I.. 1. a

    .

    11 '

    on II '' c . 11

    0.1 0) 0.J o a a CL

    Z., =II 1/1 . A 7 -0 . n- -

    H C =

    V v, ro E c

    ,_ o -o ,,_ a. 0 I 0 2 -II

    -

    II 6.. CU L .) 4) I CU 'ED E .o cn E _ca `.'\' 0 m v 70 v ro C A

    II -= I I - ' A. 4 - IC A >

    T1 . I - . a, u., z _c!) 11 0 1:2 7 E

    -0 0- ro _o 0. m 0. *.= re c ro 0 .L-.... ,c ,

    7 V -\:", V V v 7 E 0 V

    A E

    V

    0 ..) o ro 0_ 0 Z <

    cu 7

    1./1. - .

    6 Et, 2 773 QJ 4:._ CU r

    -C CI)0

    ..

    e ,Z

    i .1... n;

    To =

    a) Y `,,-.1:,

    a - - i"" al i = , r ). c 11- E 8 a a_ -c -5-. -0 a., H CL 03 u CL 0- 37.. '2 6 V C

    -z.-.. iro ,,, in. II cu c

    o o L I E ..,)

    a, C o -CL.I ...: 'al E 8

    -- ,L7 ,17.1. O 4- 1 2 ..;,. 0. - -7 cc L- .7- 6

    0 1 La *u o 0 z o , n 1 2 0.) _') O co c..,

    C1) C I I I

    r. >- 0 E v) v) 1-0 Tr,- E 1.---- o -- a, II N CU U .E. 0 0 L71.1 ''' I

    I D- 1 11- I r E>. 7,2 1 ...... 7ccil ,... wa j,,, ._.... tr).)_`11 lt:1 .1 co _a -to ;) tn. V* II II .-.-. II II ,... ... ,., vci ..

    a- -0 o a., 0 cu 6 _c = -

    .47 Mo. crz c'2' E

    o. ' -v). v). -v). r. 0 '

    V .c F, A

    chec

    kLog

    in.ph

    p

  • Site Definition tot awns ,

    Preso Advanced

    iii

    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

    What vontAl you like ia name you sire'

    Ezetole. MySite

    Prepared by Mohd Lezam Lehat UiTM 2011

    BASIC DREAMWEAVER

    A. Default interface

    tr. So. . ite

    0 P- Code Code& Design

    Design

    B. Define Site

    1. Click 'Define a site' -4 enter your name site Click Next

  • Site Definition for aims 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.

    ythich soma technology? VtH1F-ICS9T--

    ' I

    Ned.. Carve) Help

    ' Site Definition Tor aims

    Paso Advanced

    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

    Whete on you compute do you want to non your Iles?

    Vic`. r_

    Prepared by Mohd Lezam Lehat UiTM 2011

    2. Choose server technology and PHP MySQL click Next

    3. Choose 'Edit and test locally' -> Select your folder in root folder (Note : Normally in C:Ixampphtdocs\ or c:\inetpub\wwwroot\ )

  • Site Definition for aims

    EWA Advanced .

    Site Definition

    EdamF Testing Files, Past 2 SharingHes

    Dteamweaves corm...eves .ails you testing twit; using NTT P buel to krini the UAL N yore Nes Fixit

    What URL would you use to blow. to the mot ot your see? http.//locathost/ams

    Exarnole. hapl/SetverOne/Floof oldes/

    lest URL ._ '.

    a blowteri to I needt

    fad. Nora a Cancel Help

    Site Definition for 611,S

    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 f Nq> ,

    Prepared by Mohd Lezam Lehat UiTM 2011

    4. Enter URL (Note :http://localhost/RootFolder

    OR http://127.0.0.1/RootFolder )

    5. Choose 'i want to use remote server' - click next

  • Site Definition for aims

    Bask Advanced

    Site Definition

    biting hies Testre Nes Sharing hies, Part 2.

    How do you connect to you, remote tetvet ,

    Local/Netwak

    What olden onto.. servo do you wad to Om yua tics in?

    DAorcaectNedlIS syeterd

    Pefreth Remote Pk Lot Avtoolaboali

    ask Nee>

    Hek,

    Site Definition for aims

    Bask Advanced

    Site Definition

    Exiting Files Testing Files Skating Vries, Part 3

    Do you ware to enaisk chedung wand checking al t Sec, to ensue that you and you( cwvavn cannot edi de same fit at the :ow tee?

    Yes. enable check in and check co.a.

    *IP OOkonOlO the _n end check 94C

    k Nee Celled H*

    Prepared by Mohd Lezam Lehat UiTM 2011

    6. Choose 'local/network' --> select folder for remote

    7. Choose 'No' click Next

  • Prepared by Mohd Lezam Lehat UiTM 2011

    8. Finish

    Site Definition for aims

    ask I Adversoed

    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

  • TENTATIF PROGRAM

    TAJUK : Bengkel Explorasi PHP dan MySQL

    TARIKH : 28-29 JANUAR! 2012

    TEMPAT : MAKMAL KOMPUTER SL, UiTM KAMPUS SEGAMAT

    Tallith Masa AktIvIti

    SABTU

    28 Jan 2012

    5.00 ptq

    8.00 pagi Pendaftaran

    8.30 pagi MySQL Basic - Intro - CREATE database, table - INSERT and SELECT

    10.00 pagi Rehat 10.30 pagi MySQL Basic(samb)

    - Update and DELETE - phpMyAdmin

    12.30 tgh Rehat & Solat

    2.00 ptg

    PHP Editor - WYSIWYG editor

    PHP Basic - Intro - PHP Syntax, Operator &

    conditional statement. PHP Basic (samb)

    - Looping - Function

    Bersurai 8.00 pagi Pendaftaran

    8.30 pagi PHP Basic (samb)

    - Form handling - Session and cookies

    10.00 pagi Rehat

    29 Jan 2012 10.30 pagi

    view data.

    . PHP Applica t ion on - Simple Menu, add and

    12.30 tgh Rehat 8, Solat

    2.00 ptg PHP Application(samb)

    - Delete and search - Project / Tips

    5.00 ptq Bersurai

    Page 1Page 2Page 3Page 4Page 5Page 6Page 7Page 8Page 9Page 10Page 11Page 12Page 13Page 14Page 15Page 16Page 17Page 18Page 19Page 20Page 21Page 22Page 23Page 24Page 25Page 26Page 27Page 28Page 29Page 30Page 31Page 32Page 33Page 34Page 35Page 36Page 37Page 38Page 39Page 40Page 41Page 42Page 43Page 44Page 45Page 46Page 47Page 48Page 49Page 50Page 51Page 52Page 53Page 54Page 55Page 56Page 57Page 58Page 59Page 60Page 61

of 61/61
php) Quick Start: PHP for Beginner Module Prepared by : Mohd Lezam Lehat (Bsc.Comp, Msc.IT)
Embed Size (px)
Recommended