PHP Introduction. Some info on MySQL which we will cover in the next workshop...

Similar documents
PHP. M hiwa ahamad aziz Raparin univercity. 1 Web Design: Lecturer ( m hiwa ahmad aziz)

What is PHP? [1] Figure 1 [1]

What is MySQL? [Document provides the fundamental operations of PHP-MySQL connectivity]

PHP Development - Introduction

Let's Look Back. We talked about how to create a form in HTML. Forms are one way to interact with users

PHP 5 if...else...elseif Statements

Chapter 7:- PHP. Compiled By:- Sanjay Patel Assistant Professor, SVBIT.

PHP INTERVIEW QUESTION-ANSWERS

PHP 5 Introduction. What You Should Already Know. What is PHP? What is a PHP File? What Can PHP Do? Why PHP?

php Mr. Amit Patel Hypertext Preprocessor Dept. of I.T.

PHP by Pearson Education, Inc. All Rights Reserved.

Princess Nourah bint Abdulrahman University. Computer Sciences Department

Princess Nourah bint Abdulrahman University. Computer Sciences Department

PHP. Introduction. PHP stands for PHP: Hypertext Preprocessor PHP is a server-side scripting language, like ASP PHP scripts are executed on the server

The PHP language. Teaching you everything about PHP? Not exactly Goal: teach you how to interact with a database via web

Chapter 6 Part2: Manipulating MySQL Databases with PHP

Important Points about PHP:

PHP for PL/SQL Developers. Lewis Cunningham JP Morgan Chase

Web Engineering (Lecture 08) WAMP

A QUICK GUIDE TO PROGRAMMING FOR THE WEB. ssh (then type your UBIT password when prompted)

Hello everyone! Page 1. Your folder should look like this. To start with Run your XAMPP app and start your Apache and MySQL.

Web Application Development (WAD) V th Sem BBAITM(Unit-1) By: Binit Patel

Database Connectivity using PHP Some Points to Remember:

B. V. Patel Institute of BMC & IT 2014

More loops. Control structures / flow control. while loops. Loops / Iteration / doing things over and over and over and over...

Introduction of PHP Created By: Umar Farooque Khan

COM1004 Web and Internet Technology

By the end of this section of the practical, the students should be able to:

PHP with data handling

Course Topics. The Three-Tier Architecture. Example 1: Airline reservations. IT360: Applied Database Systems. Introduction to PHP

PHP. MIT 6.470, IAP 2010 Yafim Landa

CERTIFICATE IN WEB PROGRAMMING

Course Topics. IT360: Applied Database Systems. Introduction to PHP

Course Syllabus. Course Title. Who should attend? Course Description. PHP ( Level 1 (

Distributed Databases and Remote Access to a Database

Server side scripting and databases

PHP Reference. To access MySQL manually, run the following command on the machine, called Sources, where MySQL and PhP have been installed:

CSC Web Programming. Introduction to JavaScript

Arithmetic and Assignment Operators

PHP Hypertext Preprocessor

Chapter 2: Functions and Control Structures

This is CS50. Harvard College Fall Quiz 1 Answer Key

PHP Tutorial 6(a) Using PHP with MySQL

IELM 511 Information Systems Design Labs 5 and 6. DB creation and Population

PHP 1. Introduction Temasek Polytechnic

Form Processing in PHP

<form>. input elements. </form>

Databases on the web

Lecture 7: Web hacking 3, SQL injection, Xpath injection, Server side template injection, File inclusion

PHP: Cookies, Sessions, Databases. CS174. Chris Pollett. Sep 24, 2008.

Web Programming. Dr Walid M. Aly. Lecture 10 PHP. lec10. Web Programming CS433/CS614 22:32. Dr Walid M. Aly

I n p u t. This time. Security. Software. sanitization ); drop table slides. Continuing with. Getting insane with. New attacks and countermeasures:

Princess Nourah bint Abdulrahman University. Computer Sciences Department

PHP can also increase your productivity enormously, both in development time and maintenance time.

PHP and MySQL for Dynamic Web Sites. Intro Ed Crowley

CPSC 481: CREATIVE INQUIRY TO WSBF

Activity 1.1: Indexed Arrays in PHP

JavaScript Functions, Objects and Array

Create Basic Databases and Integrate with a Website Lesson 3

BEGINNER PHP Table of Contents

HTML 5 Form Processing

CGS 3066: Spring 2015 JavaScript Reference

Flow Control. Copyleft 2005, Binnur Kurt

1/22/2017. Chapter 2. Functions and Control Structures. Calling Functions. Objectives. Defining Functions (continued) Defining Functions

Server side basics CS380

JavaScript s role on the Web

CHAPTER 10. Connecting to Databases within PHP

Web Application Development (WAD) V th Sem BBAITM (Unit 4) By: Binit Patel

PHP. How Web Applications interact with server side databases CRUD. Connecting and using mysql from PHP PHP provides many mysql specific functions

Computer Components. Software{ User Programs. Operating System. Hardware

WEB SECURITY WORKSHOP TEXSAW Presented by Solomon Boyd and Jiayang Wang

Fachgebiet Technische Informatik, Joachim Zumbrägel

USQ/CSC2406 Web Publishing

LAMP Apps. Overview. Learning Outcomes: At the completion of the lab you should be able to:

Subject Name: Advanced Web Programming Subject Code: (13MCA43) 1. what is PHP? Discuss different control statements

Alpha College of Engineering and Technology. Question Bank

Programming for the Web with PHP

Web Scripting using PHP

CMPS 401 Survey of Programming Languages

You can also set the expiration time of the cookie in another way. It may be easier than using seconds.

CSCB20 Week 8. Introduction to Database and Web Application Programming. Anna Bretscher* Winter 2017

Developing Online Databases and Serving Biological Research Data

COMP284 Scripting Languages Lecture 11: PHP (Part 3) Handouts

Varargs Training & Software Development Centre Private Limited, Module: HTML5, CSS3 & JavaScript

Agenda. 1. Brief History of PHP. 2. Getting started. 3. Examples

3 The Building Blocks: Data Types, Literals, and Variables

Lecture 7 PHP Basics. Web Engineering CC 552

// Introducing PHP. Overview of Dynamic Sites with PHP and Top 5 Best Practices. WebTechNY September 10 th, 2008

Introduction. Server-side Techniques. Introduction. 2 modes in the PHP processor:

LECTURE 5 Control Structures Part 2

ITS331 IT Laboratory I: (Laboratory #11) Session Handling

Web Focused Programming With PHP

PHP. Interactive Web Systems

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 2: SEP. 8TH INSTRUCTOR: JIAYIN WANG

Binghamton University. CS-211 Fall Syntax. What the Compiler needs to understand your program

CS Homework 6. Deadline. Purpose. How to submit. Important notes. Problem 1. Spring CS Homework 6 p. 1

Lecture 2 Unix and PHP. INLS 523 Web Databases Spring 2013 Rob Capra

Chapter. Accessing MySQL Databases Using PHP

PHP Personal Home Page PHP: Hypertext Preprocessor (Lecture 35-37)

PHP Dynamic Web Pages, Without Knowing Beans

Transcription:

PHP and MYSQL

PHP Introduction PHP is a recursive acronym for PHP: Hypertext Preprocessor -- It is a widely-used open source general-purpose serverside scripting language that is especially suited for web development and can be embedded into HTML.

PHP Introduction > PHP is a server-side scripting language > PHP scripts are executed on the server > PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, etc.) > PHP is open source software > PHP is free to download and use

PHP Introduction > PHP runs on different platforms (Windows, Linux, Unix, etc.) > 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 > PHP is easy to learn and runs efficiently on the server side

PHP Introduction Some info on MySQL which we will cover in the next workshop... > MySQL is a database server > MySQL is ideal for both small and large applications > MySQL supports standard SQL > MySQL compiles on a number of platforms > MySQL is free to download and use

PHP Introduction Instead of lots of commands to output HTML (as seen in C or Perl), PHP pages contain HTML with embedded code that does "something" (like in the next slide, it outputs "Hi, I'm a PHP script!"). The PHP code is enclosed in special start and end processing instructions <?php and?> that allow you to jump into and out of "PHP mode."

PHP Introduction

PHP Introduction PHP code is executed on the server, generating HTML which is then sent to the client. The client would receive the results of running that script, but would not know what the underlying code was. A visual, if you please...

PHP Introduction

PHP Getting Started On windows, you can download and install XAAMP. With one installation and you get an Apache webserver, database server and php.

PHP Hello World Above is the PHP source code.

PHP Hello World It renders as HTML that looks like this:

PHP Hello World This program is extremely simple and you really did not need to use PHP to create a page like this. All it does is display: Hello World using the PHP echo() statement. Think of this as a normal HTML file which happens to have a set of special tags available to you that do a lot of interesting things.

In PHP, we use // to make a single-line comment or /* and */ to make a large comment block. PHP Comments

PHP Variables > Variables are used for storing values, like text strings, numbers or arrays. > When a variable is declared, it can be used over and over again in your script. > All variables in PHP start with a $ sign symbol. > The correct way of declaring a variable in PHP:

PHP Variables > In PHP, a variable does not need to be declared before adding a value to it. > 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 its value.

PHP Variables > A variable name must start with a letter or an underscore "_" -- not a number > A variable name can only contain alpha-numeric characters, underscores (a-z, 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 an underscore ($my_string) or with capitalization ($mystring)

PHP Variables Scope PHP has three different variable scopes: local global static

Local Scope A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function: <?php function mytest() { $x = 5; // local scope echo "<p>variable x inside function is: $x</p>"; } mytest(); // using x outside the function will generate an error echo "<p>variable x outside function is: $x</p>";?>

Global Scope A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function: <?php $x = 5; // global scope function mytest() { // using x inside this function will generate an error echo "<p>variable x inside function is: $x</p>"; } mytest(); echo "<p>variable x outside function is: $x</p>";?>

PHP The global Keyword The global keyword is used to access a global variable from within a function. <?php $x = 5; $y = 10; function mytest() { global $x, $y; $y = $x + $y; } mytest(); echo $y; // outputs 15?>

Global Variables PHP also stores all global variables in an array called $GLOBALS[index]. The index holds the name of the variable. <?php $x = 5; $y = 10; function mytest() { $GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y']; } mytest(); echo $y; // outputs 15?>

PHP The static Keyword Normally, when a function is completed/executed, all of its variables are deleted. However, sometimes we want a local variable NOT to be deleted. We need it for a further job. <?php function mytest() { static $x = 0; echo $x; $x++; } mytest(); mytest(); mytest();?>

PHP Concatenation > The concatenation operator (.) is used to put two string values together. > To concatenate two string variables together, use the concatenation operator:

PHP Concatenation The output of the code on the last slide will be: If we look at the code you see that we used the concatenation operator two times. This is because we had to insert a third string (a space character), to separate the two strings.

PHP Operators Operators are used to operate on values. There are four classifications of operators: > Arithmetic > Assignment > Comparison > Logical

PHP Operators

PHP Operators

PHP Operators

PHP Operators

PHP Conditional Statements > Very often when you write code, you want to perform different actions for different decisions. > You can use conditional statements in your code to do this. > In PHP we have the following conditional statements...

PHP Conditional Statements > if statement - use this statement to execute some code only if a specified condition is true > if...else statement - use this statement to execute some code if a condition is true and another code if the condition is false > if...elseif...else statement - use this statement to select one of several blocks of code to be executed > switch statement - use this statement to select one of many blocks of code to be executed

PHP Conditional Statements The following example will output "Have a nice weekend!" if the current day is Friday:

PHP Conditional Statements Use the if...else statement to execute some code if a condition is true and another code if a condition is false.

PHP Conditional Statements If more than one line should be executed if a condition is true/false, the lines should be enclosed within curly braces { }

PHP Conditional Statements 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!":

PHP Conditional Statements Use the switch statement to select one of many blocks of code to be executed.

PHP Conditional Statements For switches, first we have a single expression n (most often a variable), that is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed. Use break to prevent the code from running into the next case automatically. The default statement is used if no match is found.

PHP Conditional Statements

PHP Arrays > An array variable is a storage area holding a number or text. The problem is, a variable will hold only one value. > An array is a special variable, which can store multiple values in one single variable.

PHP Arrays If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:

PHP Arrays > However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300? > The best solution here is to use an array. > An array can hold all your variable values under a single name. And you can access the values by referring to the array name. > Each element in the array has its own index so that it can be easily accessed.

PHP Arrays In PHP, there are three kind of arrays: > Numeric array - An array with a numeric index > Associative array - An array where each ID key is associated with a value > Multidimensional array - An array containing one or more arrays

PHP Numeric Arrays > A numeric array stores each array element with a numeric index. > There are two methods to create a numeric array.

PHP Numeric Arrays In the following example the index is automatically assigned (the index starts at 0): In the following example we assign the index manually:

PHP Numeric Arrays In the following example you access the variable values by referring to the array name and index: The code above will output:

PHP Associative Arrays > With an associative array, each ID key is associated with a value. > When storing data about specific named values, a numerical array is not always the best way to do it. > With associative arrays we can use the values as keys and assign values to them.

PHP Associative Arrays In this example we use an array to assign ages to the different persons: This example is the same as the one above, but shows a different way of creating the array:

PHP Associative Arrays

PHP Multidimensional Arrays In a multidimensional array, each element in the main array can also be an array. And each element in the sub-array can be an array, and so on.

PHP Multidimensional Arrays

PHP Multidimensional Arrays

PHP Multidimensional Arrays

PHP Loops > Often when you write code, you want the same block of code to run over and over again in a row. Instead of adding several almost equal lines in a script we can use loops to perform a task like this. > In PHP, we have the following looping statements:

PHP Loops > while - loops through a block of code while a specified condition is true > do...while - loops through a block of code once, and then repeats the loop as long as a specified 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

PHP Loops - While The while loop executes a block of code while a condition is true. The example below defines a loop that starts with i=1. The loop will continue to run as long as i is less than, or equal to 5. i will increase by 1 each time the loop runs:

PHP Loops - While

PHP Loops Do... While The do...while statement will always execute the block of code once, it will then check the condition, and repeat the loop while the condition is true. The next example defines a loop that starts with i=1. It will then increment i with 1, and write some output. Then the condition is checked, and the loop will continue to run as long as i is less than, or equal to 5:

PHP Loops Do... While

PHP Loops Do... While

PHP Loops - For

PHP Loops - For Parameters: > init: Mostly used to set a counter (but can be any code to be executed once at the beginning of the loop) > condition: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends. > increment: Mostly used to increment a counter (but can be any code to be executed at the end of the loop)

PHP Loops - For The example below defines a loop that starts with i=1. The loop will continue to run as long as i is less than, or equal to 5. i will increase by 1 each time the loop runs:

PHP Loops - For

PHP Loops - Foreach For every loop iteration, the value of the current array element is assigned to $value (and the array pointer is moved by one) - so on the next loop iteration, you'll be looking at the next array value.

PHP Loops - Foreach The following example demonstrates a loop that will print the values of the given array:

PHP Loops - Foreach

PHP Functions > We will now explore how to create your own functions. > To keep the script from being executed when the page loads, you can put it into a function. > A function will be executed by a call to the function. > You may call a function from anywhere within a page.

PHP Functions A function will be executed by a call to the function. > Give the function a name that reflects what the function does > The function name can start with a letter or underscore (not a number)

PHP Functions A simple function that writes a name when it is called:

PHP Functions - Parameters Adding parameters... > To add more functionality to a function, we can add parameters. A parameter is just like a variable. > Parameters are specified after the function name, inside the parentheses.

PHP Functions - Parameters

PHP Functions - Parameters

PHP Functions - Parameters This example adds different punctuation.

PHP Functions - Parameters

PHP Default Argument Value If we call the function setheight() without arguments it takes the default value as argument: <?php function setheight($minheight = 50) { echo "The height is : $minheight <br>"; } setheight(350); setheight(); // will use the default value of 50 setheight(135); setheight(80);?>

PHP Functions - Returning values To let a function return a value, use the return statement: <?php function sum($x, $y) { $z = $x + $y; return $z; } echo "5 + 10 = ". sum(5, 10). "<br>"; echo "7 + 13 = ". sum(7, 13). "<br>"; echo "2 + 4 = ". sum(2, 4);?>

PHP Global Variables - Superglobals Several predefined variables in PHP are "superglobals", which means that they are always accessible, regardless of scope - and you can access them from any function, class or file without having to do anything special.

PHP superglobal variables The PHP superglobal variables are: $GLOBALS $_SERVER $_REQUEST $_POST $_GET $_FILES $_ENV $_COOKIE $_SESSION

PHP $GLOBALS $GLOBALS is a PHP super global variable which is used to access global variables from anywhere in the PHP script (also from within functions or methods). PHP stores all global variables in an array called $GLOBALS[index]. The index holds the name of the variable.

PHP $GLOBALS Example <?php $x = 75; $y = 25; function addition() { $GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y']; } addition(); echo $z;?>

PHP $_SERVER $_SERVER is a PHP super global variable which holds information about headers, paths, and script locations. <?php echo $_SERVER['PHP_SELF']; echo "<br>"; echo $_SERVER['SERVER_NAME']; echo "<br>"; echo $_SERVER['HTTP_HOST']; echo "<br>"; echo $_SERVER['SCRIPT_NAME'];?>

The following table lists the most important elements that can go inside $_SERVER: Element/Code $_SERVER['PHP_SELF'] $_SERVER['SCRIPT_FILENAME'] $_SERVER['SERVER_ADDR'] Description Returns the filename of the currently executing script Returns the absolute pathname of the currently executing script Returns the IP address of the host server $_SERVER['SERVER_NAME'] Returns the name of the host server $_SERVER['SERVER_SOFTWARE'] $_SERVER['SERVER_PROTOCOL'] $_SERVER['REQUEST_METHOD'] Returns the server identification string (such as Apache/2.2.24) Returns the name and revision of the information protocol (such as HTTP/1.1) Returns the request method used to access the page (such as POST)

PHP Forms - $_GET Function > The built-in $_GET function is used to collect values from a form sent 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 has limits on the amount of information to send (max. 100 characters).

PHP Forms - $_GET Function Notice how the URL carries the information after the file name.

PHP Forms - $_GET Function The "welcome.php" file can now use the $_GET function to collect form data (the names of the form fields will automatically be the keys in the $_GET array)

PHP Forms - $_GET Function > When using method="get" in HTML forms, all variable names and values are displayed in the URL. > 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. > The get method is not suitable for large variable values; the value cannot exceed 100 chars.

PHP Forms - $_POST Function > The built-in $_POST function is used to collect values from a form sent 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. > Note: However, there is an 8 Mb max size for the POST method, by default (can be changed by setting the post_max_size in the php.ini file).

PHP Forms - $_POST Function And here is what the code of action.php might look like:

PHP Forms - $_POST Function Apart from htmlspecialchars() and (int), it should be obvious what this does. htmlspecialchars() makes sure any characters that are special in html are properly encoded so people can't inject HTML tags or Javascript into your page. For the age field, since we know it is a number, we can just convert it to an integer which will automatically get rid of any stray characters. The $_POST['name'] and $_POST['age'] variables are automatically set for you by PHP.

PHP Forms - $_POST Function When to use 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. > However, because the variables are not displayed in the URL, it is not possible to bookmark the page.

PHP Form Validation

The Form Element The HTML code of the form looks like this: <form method="post" action="<?php echo htmlspecialchars($_server["php_self"]);?>">

PHP Form Validation $_SERVER["PHP_SELF"] variable? The $_SERVER["PHP_SELF"] is a super global variable that returns the filename of the currently executing script. htmlspecialchars() function? The htmlspecialchars() function converts special characters to HTML entities. This means that it will replace HTML characters like < and > with < and >. This prevents attackers from exploiting the code by injecting HTML or Javascript code (Cross-site Scripting attacks) in forms.

REQUIRED FIELD if (empty($_post["name"])) { $nameerr = "Name is required"; } else { $name = $_POST["name"]; } DISPLAY ERROR MESSAGE <form method="post" action="<?php echo htmlspecialchars($_server["php_self"]);?> "> Name: <input type="text" name="name"> <span class="error">* <?php echo $nameerr;?></span><br>

PHP - Validate Name $name = $_POST["name"]; if (!preg_match("/^[a-za-z ]*$/",$name)) { $nameerr = "Only letters and white space allowed"; } The preg_match() function searches a string for pattern, returning true if the pattern exists, and false otherwise.

PHP - Validate E-mail $email = $_POST["email"]; if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $emailerr = "Invalid email format"; } The easiest and safest way to check whether an email address is well-formed is to use PHP's filter_var() function.

PHP - Validate URL The code below shows a way to check if a URL address syntax is valid (this regular expression also allows dashes in the URL). $website = $_POST["website"]; if (!preg_match("/\b(?:(?:https? ftp):\/\/ www\.)[- a-z0-9+&@#\/%?=~_!:,.;]*[-a-z0-9+&@#\/%=~_ ]/i",$website)) { $websiteerr = "Invalid URL"; }

PHP And MySQL MySQL is the most popular open-source database system.

Connecting to Database 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 servername username 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 password Optional. Specifies the password to log in with. Default is ""

Establishing and Closing the connection <?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('could not connect: '. mysql_error()); } // some code mysql_close($con);?> die - Output a message and terminate the current script

Create a Database The CREATE DATABASE statement is used to create a database in MySQL. Syntax CREATE DATABASE database_name To get PHP to execute the statement above we must use the mysql_query() function. This function is used to send a query or command to a MySQL connection.

mysql_close($con);?> Create a Database <?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('could not connect: '. mysql_error()); } if (mysql_query("create DATABASE my_db",$con)) { echo "Database created"; } else { echo "Error creating database: ". mysql_error(); }

<?php Create a Table //Create database mysql_select_db("my_db", $con);//select database //create table $sql = "CREATE TABLE Persons ( FirstName varchar(15), LastName varchar(15), Age int )"; mysql_query($sql,$con); // Execute query mysql_close($con); // Close Connection

Insert Data Into a Database Table <?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('could not connect: '. mysql_error()); }

Insert Data Into a Database Table mysql_select_db("my_db", $con); mysql_query("insert INTO Persons (FirstName, LastName, Age) VALUES ('Peter', 'Griffin', 35)"); mysql_query("insert INTO Persons (FirstName, LastName, Age) VALUES ('Glenn', 'Quagmire', 23)"); mysql_close($con);?>

Insert Data From a Form Into a HTML form: Database <html> <body> <form action="insert.php" method="post"> Firstname: <input type="text" name="firstname" /> Lastname: <input type="text" name="lastname" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> </body> </html>

Insert Data From a Form Into a "insert.php" page: Database <?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('could not connect: '. mysql_error()); } mysql_select_db("my_db", $con);

Insert Data From a Form Into a Database $sql="insert INTO Persons (FirstName, LastName, Age) VALUES ('$_POST[firstname]','$_POST[lastname]', $_POST[age])"; if (!mysql_query($sql,$con)) { die('error: '. mysql_error()); } mysql_close($con)?>

Select Data From a Database Table <?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('could not connect: '. mysql_error()); } mysql_select_db("my_db", $con);

Select Data From a Database Table $result = mysql_query("select * FROM Persons"); while($row = mysql_fetch_array($result)) { echo $row['firstname']. " ". $row['lastname']; echo "<br />"; } mysql_close($con);?>

Explanation - The example stores the data returned by the mysql_query() function in the $result variable. - mysql_fetch_array Fetch a result row as an associative array, a numeric array, or both - Next, we use the mysql_fetch_array() function to return the first row from the recordset as an array. Each call to mysql_fetch_array() returns the next row in the recordset. The while loop loops through all the records in the recordset.