+ All Categories
Home > Engineering > PHP and MySQL with snapshots

PHP and MySQL with snapshots

Date post: 24-May-2015
Category:
Upload: richambra
View: 215 times
Download: 5 times
Share this document with a friend
Popular Tags:
71
PHP By: Kunika Verma
Transcript
Page 1: PHP and MySQL with snapshots

PHP

By: Kunika Verma

Page 2: PHP and MySQL with snapshots

Introduction

PHP is an acronym for "PHP Hypertext Preprocessor“.PHP is a widely-used, open source scripting language.PHP scripts are executed on the server.PHP costs nothing, it is free to download and use.PHP is simple for beginners.PHP also offers many advanced features for professional programmers.

What is a PHP File?PHP files can contain text, HTML, CSS, JavaScript, and PHP code.PHP code are executed on the server, and the result is returned to the browser as plain HTML.PHP files have extension ".php“.

Page 3: PHP and MySQL with snapshots

Why PHPPHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)PHP supports a wide range of databases.PHP is free. Download it from the official PHP resource: www.php.net.PHP is easy to learn and runs efficiently on the server side.

How to run PHP files? localhost/foldername/filenameResource:

Xampp Combines an Apache web server, PHP, and MySQL into one

simple installation service. Very little configuration required by the user to get an initial

system up and running. http://www.apachefriends.org/en/xampp.html

Page 4: PHP and MySQL with snapshots

Variables in PHP

Page 5: PHP and MySQL with snapshots

Variables in PHP

Variables in PHP are denoted by a dollar ($) sign followed by the name of the variable. Variable names are case sensitive ($y and $Y are two different variables).A variable name cannot start with a number.A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores.

Page 6: PHP and MySQL with snapshots

Example Usage of Variables

Page 7: PHP and MySQL with snapshots

Output:

Page 8: PHP and MySQL with snapshots

Arrays in PHP

Page 9: PHP and MySQL with snapshots

An array can store one or more values in a single variable name.Each element in the array is assigned its own ID so that it can be easily accessed.$array[key] = value;An array in PHP is a structure which maps keys to values .The keys can specified explicitly or they can be omitted.If keys are omited, integers starting with 0 are keys.The value mapped to a key can, itself, be an array, so we can have nested arrays.

Page 10: PHP and MySQL with snapshots

Types of Arrays

Page 11: PHP and MySQL with snapshots

Numeric Array

An Array with numeric index.A numeric array stores each element with a numeric ID key.

Automatically array:Example:$names = array("Peter","Quagmire","Joe");

Page 12: PHP and MySQL with snapshots

Manually array

<?php $lang[0]="PHP"; $lang[1]="Perl"; $lang[2]="Java"; $lang[3]=".Net"; echo "<b>" .$lang[0]. " and " .$lang[1]. " are programming languages.";?>

Page 13: PHP and MySQL with snapshots

Associative Array

An array where each ID key is associated with a value.An array with strings index. This stores element values in association with key values rather than in a strict linear index order.When storing data about specific named values, a numerical array is not always the best way to do it.It is the combination of keys and values. Associative array will have their index as string so that you can establish a strong association between key and values.

Syntax:

$arr_name=array(“key”=>value, “key”=>value);

Page 14: PHP and MySQL with snapshots

Example:

<?php $lang ['php']="10"; $lang ['perl']="5"; $lang ['java']="2"; echo "php language is ".$lang ['perl']. "years old."; ?>

Page 15: PHP and MySQL with snapshots

Multidimensional Array

An array containing one or more array.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.

Syntax:

$ main_Array=array(“sub-array=>array(“PHP”,“perl”));

Page 16: PHP and MySQL with snapshots

Example: <?php $array=array( "php"=>array( "php1", "php", "php5" ), "perl"=>array( "perl5" ) ); echo "<b>". "Is " . $array ["perl"][0] . " programming language?";?>

Page 17: PHP and MySQL with snapshots

Array-manupulation functions

PHP provides a huge set of array-manipulation functions. Some of them are given below:array -- Create an array Mixed_array –integers and stringscurrent_array-Return the current elements in the arrayarray_key_exists -- Checks if the given key or index exists in the arrayarray_keys -- Return all the keys of an arrayarray_merge -- Merge two or more arraysarray_merge_recursive -- Merge two or more arrays recursively

array_walk -- Apply a user function to every member of an array arsort -- Sort an array in reverse order and maintain index association asort -- Sort an array and maintain index associationcompact -- Create array containing variables and their values count -- Count elements in a variablecurrent -- Return the current element in an array

.

Page 18: PHP and MySQL with snapshots

Examples: Array count

<?php $a[0]=1; $a[1]=2; $a[2]=5; $result= count($a); echo $result; ?>

Page 19: PHP and MySQL with snapshots

Combine array

Creates an array by using one array for keys and another for its value Example: <?php $a=array("green","red", "yelllow");$b=array("avocoda","apple","banana");$c=array_combine($a,$b);print_r($c);?>

Page 20: PHP and MySQL with snapshots

Array Sort Sort an array (according to alphabet) Example: <?php $fruits=array("lemon","orange","banana"); sort($fruits); foreach ($fruits as $keys =>$val){Echo "fruits <br>[". $keys ."]=". $val ."";}?>

Page 21: PHP and MySQL with snapshots

Strings in PHP

Page 22: PHP and MySQL with snapshots

Strings

String is a series of character. Save as bytes. A string literal can be specified in three different ways:

single quoted double quoted

Page 23: PHP and MySQL with snapshots

Single-quoted Strings

In single-quoted strings, single-quotes and backslashes must be escaped with a preceding backslashExample usage

echo 'this is a simple string';

echo 'You can embed newlines in strings, just like this.'; echo ‘Douglas MacArthur said "I\'ll be back” when leaving the

Phillipines'; echo 'Are you sure you want to delete C:\\*.*?';

Page 24: PHP and MySQL with snapshots

Double-quoted Strings

In double-quoted strings, variables are interpreted to their values, and various characters can be escaped

\n linefeed \r carriage return \t horizontal tab \\ backslash \$ dollar sign \” double quote \[0-7]{1,3} a character in octal notation \x[0-9A-Fa-f]{1,2} a character in hexadecimal

notation

Page 25: PHP and MySQL with snapshots

String-manipulation functions

PHP provides huge range of string-manipulation functions:

addcslashes -- Quote string with slashes in a C style addslashes -- Quote string with slashes count_chars -- Return information about characters used

in a string echo -- Output one or more strings. explode -- Split a string by string implode -- Join array elements with a string join -- Join array elements with a string ltrim -- Strip whitespace from the beginning of a string md5 -- Calculate the md5 hash of a string strpos -- Find position of first occurrence of a string

Page 26: PHP and MySQL with snapshots

stristr -- Case-insensitive strstr() strrchr -- Find the last occurrence of a character in a string str_repeat -- Repeat a string strrev -- Reverse a string strrpos -- Find position of last occurrence of a char in a string strspn -- Find length of initial segment matching mask strstr -- Find first occurrence of a string strtolower -- Make a string lowercase strtoupper -- Make a string uppercase str_replace -- Replace all occurrences of the search string with

the replacement string strncmp -- Binary safe string comparison of the first n

characters

Some examples are given next:

Page 27: PHP and MySQL with snapshots

Examples: strlen: Get string length.it also

include space.It counts from 1.

<?php $str="bebo technology"; $result=strlen ($str); echo "the string length is

$result"; echo "<br>"; ?> Syntax: strlen(string);

Page 28: PHP and MySQL with snapshots

Examples Strpos

This function return the position of

particular character in string. It counts from 0.

Example: <?php $numbered_string="1234567890";

$five_pos=strpos($numbered_string, "5");

echo "the position of 4 in our string is " . $five_pos;

?>Syntax:Strpos(string,”char position to be

found”)

Page 29: PHP and MySQL with snapshots

Examples: explode function

The explode function break a string Into array.

<?php $array="welcome to btes"; print_r (explode (" ","$array")); ?> Syntax: explode (seprator,string);

Page 30: PHP and MySQL with snapshots

Examples: Implode function

join array elements with a string.

<?php $array=array('kunika', 'verma',

'B.tech'); $comma_seprated=implode (",

",$array); echo $comma_seprated; ?> Syntax: implode (seprator,string);

Page 31: PHP and MySQL with snapshots

Include() and require() functions

Page 32: PHP and MySQL with snapshots

INCLUDE AND REQUIRE FUNCTIONS

PHP include and require Statements

In PHP, you can insert the content of one PHP file into another PHP file before the server executes it.The include and require statements are used to insert useful codes written in other files, in the flow of execution.

Include and require are identical, except upon failure:

Require will produce a fatal error (E_COMPILE_ERROR) and stop the script.Include will only produce a warning (E_WARNING) and the script will continue.Including files saves a lot of work. This means that you can create a standard header, footer, or menu file for all your web pages. Then, when the header needs to be updated, you can only update the header include file.

Page 33: PHP and MySQL with snapshots

PHP include and require statement

Syntax:- include 'filename';

or

require 'filename';

Example:

Assume that you have a standard header file, called "header.php". To include the header file in a page, use include/require:<html><body>

<?php include 'header.php'; ?><h1>Welcome to my home page!</h1><p>Some text.</p>

</body></html>

Page 34: PHP and MySQL with snapshots

Example 2:

Assume we have a standard menu file that should be used on all pages."menu.php":echo '<a href=“#">Home</a><a href=“#">Tutorials</a><a href=“#">About Us</a> <a href=“#">Contact Us</a>';All pages in the Web site should include this menu file.<html><body><div class="leftmenu"><?php include 'menu.php'; ?></div><h1>Welcome to my home page.</h1><p>Some text.</p></body></html>

Page 35: PHP and MySQL with snapshots

PHP Looping

Page 36: PHP and MySQL with snapshots

While loop

The while loop executes a block of code as long as the specified condition is true.

Syntax:while (condition is true)  {  code to be executed;  } The example below first sets a variable $x to 1 ($x=1;). Then, the while loop will continue to run as long as $x is less than, or equal to 5. $x will increase by 1 each time the loop runs ($x++;):

Page 37: PHP and MySQL with snapshots

Example:<?php

$x=1; while($x<=5)  {  echo "The number is: $x <br>";  $x++;  } ?>

Page 38: PHP and MySQL with snapshots

Do-while loop

The do...while loop will always execute the block of code once, it will then check the condition, and repeat the loop while the specified condition is true.

Syntaxdo  {  code to be executed;  }while (condition is true); The example below first sets a variable $x to 1 ($x=1;). Then, the do while loop will write some output, and then increment the variable $x with 1. Then the condition is checked (is $x less than, or equal to 5?), and the loop will continue to run as long as $x is less than, or equal to 5:

Page 39: PHP and MySQL with snapshots

Example: <?php $x=1; do  {  echo "The number is: $x <br>";  $x++;  } while ($x<=5) ?>

Page 40: PHP and MySQL with snapshots

for: The for loop is used when you know in advance how many times the script should run.

Syntax: for (int counter; testcounter; increment counter)

  {  code to be executed;  }

Parameters:intcounter: Initialize the loop counter valuetest counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends.increment counter: Increases the loop counter value

For loop

Page 41: PHP and MySQL with snapshots
Page 42: PHP and MySQL with snapshots

foreach Loop

The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.

Syntax:foreach ($array as $value)  {  code to be executed;  } For every loop iteration, the value of the current array element is assigned to $value and the array pointer is moved by one, until it reaches the last array element.

Page 43: PHP and MySQL with snapshots

Example: <?php $a=array(1,2,3,4,5); foreach ($a as $value)

{?><div style="background-color:pink; width:50;"><?php echo $value; ?>

</div></br><?php } ?>

Page 44: PHP and MySQL with snapshots

MYSQL and PHP

Page 45: PHP and MySQL with snapshots

PHP is designed to work with the MySQL database. However, it can also connect to other database systems such as Oracle, Sybase, etc., using ODBC.Handles very large databases; very fast performance.

Why are we using MySQL?

Free (much cheaper than Oracle!) Each student can install MySQL locally. Easy to use Shell for creating tables, querying tables, etc. Easy to use with Java JDBC

Page 46: PHP and MySQL with snapshots

PHPMY ADMIN

phpMyAdmin  is a free and open source tool written in PHP intended to

handle the administration of Mysql with the use of a web browser. It can perform various tasks such as creating, modifying or deleting databases, tables, fields or rows; executing SQL statements; or managing users and permissions.

Syntax: localhost/phpmyadmin

Page 47: PHP and MySQL with snapshots

How to connect with PHP?

Use the My SQL connect routine mysql_connect($host, $user, $password) $user and $password will be your account details

Mysql_connect will return a link ID $link = mysql_connect($host, $user, $password) if(!$link) { echo “Unable to connect”; }

Always check the link to ensure that the database connection was successful

Page 48: PHP and MySQL with snapshots

Selecting a database

Once a link has been established, select a database mysql_select_db($dbname, [$link]) []optional – uses last created $link if not given

mysql_select_db returns a Boolean indicating status$result = mysql_select_db(“students”)If(!$result) { echo “No database”; }

Page 49: PHP and MySQL with snapshots
Page 50: PHP and MySQL with snapshots

How to create database in Mysql

Page 51: PHP and MySQL with snapshots

How to create tables in Mysql

Click on your database name. Then create table option will show. It all show in fig:

Page 52: PHP and MySQL with snapshots

Data Types

Page 53: PHP and MySQL with snapshots

Change the attributes

Page 54: PHP and MySQL with snapshots

Mysql Queries

Page 55: PHP and MySQL with snapshots

Query types:

Insert querySelect queryDelete queryUpdate queryJoin query

Page 56: PHP and MySQL with snapshots

INSERT Query: INSERT INTO

INSERT INTO [table]([fields,…] VALUES([newvalues,…]).[table] indicates which table to insert into.[fields] is a comma separated list of fields that are being used.[newvalues] is comma separated list of values that directly correspond to the [fields].

Syntax: “insert into managenews(fields)

(values)”;

Page 57: PHP and MySQL with snapshots

Example:

Page 58: PHP and MySQL with snapshots

In database:

Page 59: PHP and MySQL with snapshots

Selection query:

SELECT SELECT [fields,…] FROM

[table] WHERE [criteria] ORDER BY [field] [asc,desc]

[fields] can be * for all or field names separated by commas[table] is the name of the table to use.

Syntax: “select * from

managenews(tablename)”:

Page 60: PHP and MySQL with snapshots

Example:

Page 61: PHP and MySQL with snapshots

Delete Query:

DELETE DELETE FROM [table]

WHERE [criteria]Simple and dangerous statements[table] to delete from[criteria] specifying records to delete

No criteria deletes all records.

Syntax:“delete from

managenews(tablename)”;

Page 62: PHP and MySQL with snapshots

Update Query:

UPDATE UPDATE [table] SET

[field=value,…] WHERE [criteria]

[table] denotes the table to update[field=value,…] is a comma separated list of values for fieldsSyntax:

“update managenews(table name) set

(field=‘value’)”;

Quick example:

$query = “UPDATE managenews SET news='$news',date='$date‘ where id=".$id;

$result = mysql_query($query);If(!$result) {

echo “Update failed!”;} else {

echo “Update successful!”;}

Page 63: PHP and MySQL with snapshots

Join Query:

JOINs can be used to combine tables.A join can be classified in the from clause which list the two input relations.

Types of joins:

1) Join2) Inner join3) Outer join4) Left join5) Right join

Page 64: PHP and MySQL with snapshots

Tables for join:

Page 65: PHP and MySQL with snapshots

How to Join:

Consist full data which we Show in our Query.

Syntax: select Persons.Firstname, Persons.Lastname,

Orders.Orderno from Persons JOIN Orders ON

Persons.P_Id=Orders.P_Id

Output:

Page 66: PHP and MySQL with snapshots

Inner join:

Simplest type of join Also called: Equality join, Equijoin, Natural joinVALUES in one table equal to values in other tableSyntax:

select Persons.Firstname, Persons.Lastname,

Orders.Orderno from Persons INNER JOIN Orders ON

Persons.P_Id=Orders.P_Id

Syntax:

Page 67: PHP and MySQL with snapshots

Outer join

Outer joins return all rows from one table

(called inner table) and only matching rows from

second table (outer table)Fields are different in outer join

Syntax: select Persons.Firstname, Persons.Lastname,

Orders.Orderno from Persons OUTER JOIN Orders ON

Persons.P_Id=Orders.P_Id

Page 68: PHP and MySQL with snapshots

Left Join:

Left join pick the left outer cell data.

Syntax: select Persons.Firstname, Persons.Lastname,

Orders.Orderno from Persons LEFT JOIN Orders ON

Persons.P_Id=Orders.P_Id

Page 69: PHP and MySQL with snapshots

Important:

Distinct: Count one for duplicate enteries.Syntax: Select distinct (category) from (tablename).

Limits: limit the counting for display. Syntax: select * from products (tablename) limit 0,10

Order by: set by ascending or descending orderSyntax:Select * from (tablename) order by (productname) ASC DESCOb_start(); if we use 2 headers on same page. use before html.Ob_flush(); closing tag after html closing tag.

Page 70: PHP and MySQL with snapshots

70

Accessing Query Result Information

The mysql_num_rows() function returns the number of rows in a query resultThe mysql_num_fields() function returns the number of fields in a query resultBoth functions accept a database connection variable as an argumentThe mysql_query() function sends SQL statements to MySQLYou use the mysql_create_db() function to create a new databaseThe mysql_select_db() function selects a databaseYou use the mysql_drop_db() function to delete a databasemysql_fetch_array() for fetch array by rows.

Page 71: PHP and MySQL with snapshots

Recommended