Sei sulla pagina 1di 13

Download the code used in the lesson.

PHP_introduction.zip

Instructions to open zip file. The instructions file is present in every zip folder also.

Extract the files.

Open netbeans.

Click on file in the top menu.

Choose New Project option.

Choose PHP category and in Projects section, choose PHP Application with Existing
Source.

For Site Root, browse to the folder where you have extracted these files.

Click on finish.

The folder will open in netbeans.

Note: echo statement is not case sensitive. ECHO/echo/Echo means the same in PHP.

Boolean variables
Boolean variables contain only TRUE or FALSE as values.
$var = TRUE;
This is boolean variable. TRUE or FALSE should not be in quotes. Then it will be considered as
strings.

Arithmetic Operations
It usually includes addition, subtraction,multiplication, division, modulus which gives the
remainder of the division and exponentiation.

Example Name Result


$a + $b Addition Sum of $a and $b
$a - $b Subtraction Difference of $a and $b
$a * $b Multiplication Product of $a and $b
$a / $b Division Quotient of $a and $b
$a % $b Modulo Remainder of $a divided by $b
$a ** $b Exponentiation Result of raising $a to the $b th power. Introduced in PHP 5.6
Logical Operations
Logical operators, Relational operators are used for comparisons. These are the valid operators
for PHP. These operations either evaluate to TRUE or a FALSE state.

Example Name Result


$a and
And TRUE if both $a and $b are TRUE, FALSE otherwise
$b
TRUE if either $a or $b is TRUE. If $a is TRUE and $b is false then also this
$a || $b Or condition will output true as one of the two options or both the option should
be true in OR case
$a xor $b Xor TRUE if either $a or $b is TRUE, but not both; otherwise FALSE
! $a Not TRUE if $a is not TRUE, otherwise FALSE
$a % $b Modulo Remainder of $a divided by $b

http://www.mytoptutorials.com/php/tag/php-multidimensional-arrays/

Difference between single quotes and double quotes:

Single Quotes Double Quotes

Double quotes inside single quotes Single quotes inside double quotes will be
will be considered as strings. considered as strings.

Variables inside single quotes will be Variables inside double quotes will be
considered as strings and will display considered as variables only and will display
the variable name only. the value of the variable instead of name.

Input: Input:
$variable = 5; $variable = 5;
echo 'The output is $variable.'; echo "The output is $variable.";

Output: Output:
The output is $variable. The output is 5.

Commonly used string functions are:

strrev($string): Returns the reversed string.

strtolower($string): Returns the string with all the characters in lowercase


only.

strtoupper($string): Returns the string with all the characters in uppercase


only.
strpos($string,$find_substring,start): This fucntion finds the position of the
first occurrence of a substring in a string.
e.g. Input: echo strpos("I am a web developer", "web", 1); Output: 7.

Consider the following link of official bootstrap manual for all possible string functions in PHP.
Sting Functions

If condition could be used without else part.


if($marks == 40){
echo "Just passed";
}

If-else statement can be used inside another if else statement.


1. if($marks >= 40){
2. if($marks == 40){
3. echo "Just passed";
4. }else{
5. echo "passed";
6. }
7. }else{
8. echo "fail";
9. }
Explaination: Second if-else statement which starts at line number 2 is inside first if statement at
line number 1. If first if at line number 1 is true, then second if-else will be executed. Otherwise,
else part of first if statement at line number 7 will be executed.

mysqli_query function:
This function is used to run SQL queries in PHP. The function takes two parameters.

1. Connection variable.

2. Variable in which SQL query is stored.

This function will return the data depending upon the SQL query. This will contain data if
SELECT query is executed. It will contain boolean variable indicating TRUE (query successfully
executed )or FALSE (error in executing the query)

nstructions:

Create index.php file.


Establish the connection with the database.

Write the select query to fetch id, email and first_name from the users table (ecommerce
database).

Echo all the users data in the web page.

Note: The solution to the code challenge is available in the helpertext of previous two lessons.

nstructions:

Create index.php file.

Establish the connection to the database.

Write the select query to fetch id, email and first_name from the users table (ecommerce
database).

Use while loop to display all the users.

Use four bootstrap rows inside the while loop.

Rows will display id, email, first_name and products purchased by the user.

Define a function to fetch products purchased by the user. Function should have
connection and user id as parameter. In this function, use select query on users_products
to fetch the products of particular user by passing user id in where clause. The function
will return the count of rows fetched by the select query.

Call the function inside the while loop by passing connection and user id as parameters.
Display the response of the function.

Note: Please find the solution of the code challenge in the helper text of previous two lessons of
this topic

uidelines:
Form tag contains two attributes: action and method.

1. Action attribute consists the name of the file to which the form data will be sent. This
attribute may or maynot contain any value. If no value is mentioned or this attribute is not
mentioned in the form tag, the data will be sent to this page only.

2. Method attribute can have two values: GET or POST.


Difference between GET and POST:
GET POST
Values appear in the URL Values do not appear in the URL
Values can be bookmarked Values can not be bookmarked
There is a limit on characters which can be sent There is no limit on the characters send through
through URL. POST request.
Less secure More secure

Code and explanation of user_registration.php


<?php
//connection established
$con = mysqli_connect("localhost","root","","ecommerce") or die(mysqli_error($con));

//Store form values into variables


$email = $_POST['email'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$phone = $_POST['phone'];

//Store insert query in a variable. Use double quotes to let PHP treat variables as variables
only.
$user_registration_query = "insert into users(email, first_name, last_name, phone) values
('$email', '$first_name', '$last_name', '$phone')";

//Execute the query


$user_registration_submit = mysqli_query($con, $user_registration_query) or
die(mysqli_error($con));

//If this echo is executed, this means query successfully executed. Otherwise die function
with mysqli_query function would have stopped the execution of the code.
echo "User successfully inserted";
?>

Instructions:

Create index.php file.

Make a form with action attribute user_registration_script.php and method POST.

The form would have email, first name, last name and phone fields.

Create user_registration_script.php file.


Establish the connection to the database.

Store the users data in the variables by using $_POST variable.

Store insert query in a variable.

Use mysqli_query function to run the insert query.

Note: Please find the solution of the code challenge in the helper text of previous two lessons of
this topic.

Header function

The header() function sends a raw HTTP header to a client. In simple words, header redirects the
user to another page.
Suppose we want logged out user to open only index.php page. If logged out user tries to open
any other page, it should be redirected to index.php page.

Code:
<?php
if(!isset($_SESSION['id'])){
header('location: index.php');
exit;
}
?>

Header function takes a string parameter (location: name_of_the_web_page.php).

Header function should be used before we echo or display any HTML element because user will
be redirected as header fucntion is encountered in the code.

Code Challenge:

Store page views in the session variable.


Instructions:

Create index.php file.

Start session using session_start().

Check whether $_SESSION['views'] is set. If yes, increment the value stored in


the session by 1. Else, initialize views session and store value 1 in it.

Echo the value of the session.

Code Challenge:
Store page views in the session variable.
Instructions:

Create index.php file.

Start session using session_start().

Check whether $_SESSION['views'] is set. If yes, increment the value stored in the
session by 1. Else, initialize views session and store value 1 in it.

Echo the value of the session.

Pattern for email: [a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$


Pattern for password: .{6,}

Web Development

OVERVIEW
STUDY ROOM
HTML & CSS
Bootstrap
SQL
PHP

PHP: Introduction

Basics

Functions/Arrays/Strings

Loops

Database Connection
SELECT Query with PHP (Part I)

SELECT Query with PHP (Part II)

Form

Sessions

Basic security

Validations with HTML5/PHP

Assignment

Module Test

Final Test
PROGRESS TRACKER
TEST YOUR CODE

PHP

>

Validations with HTML5/PHP

Code Challenge:

Make a form in bootstrap with form fields name, email, date of birth (format: MM/DD/YYYY)
and password. Write HTML5 validations for the form.

Your Code

Solution

1
<!DOCTYPE html>
2
<html>
3
<head>
4
<title>HTML5 validations</title>
5
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" >
6
<!--jQuery library-->
7
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></scri
pt>
8
<!--Latest compiled and minified JavaScript-->
9
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></sc
ript>
10
<meta name="viewport" content="width=device-width, initial-scale=1">
11
</head>
12
<body>
13
<div class="container">
14
<div class="row">
15
<div class="col-xs-6 col-xs-offset-3">
16
<h4>Signup Form</h4>
17
<form >
18
<div class="form-group">
19
<input class="form-control" placeholder="Name"
name="name" required = "true" pattern="^[A-Za-z\s]{1,}[\.]{0,1}[A-Za-z\s]
{0,}$">
20
</div>
21
<div class="form-group">
22
<input type="email" class="form-control"
placeholder="Email" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$"
name="e-mail" required = "true">
23
</div>
24
<div class="form-group">
25
<input type="password" class="form-control"
placeholder="Password" pattern=".{6,}" name="password" required = "true">
26
</div>
27

28
<!-- Use date type or pattern="(?:(?:0[1-9]|1[0-2])
[\/\\-. ]?(?:0[1-9]|[12][0-9])|(?:(?:0[13-9]|1[0-2])[\/\\-. ]?30)|(?:
(?:0[13578]|1[02])[\/\\-. ]?31))[\/\\-. ]?(?:19|20)[0-9]{2}"-->
29
<div class="form-group">
30
<input type="Date" class="form-control"
placeholder="dob" name="dob" required = "true">
31
</div>
32
<button type="submit" name="submit" class="btn btn-
primary">Submit</button>
33
</form>
34
</div>
35
</div>
36
</div>
37
</body>
38
</html>

Prev
Next

Forum

Q. How to redirect to a page in PHP?

In PHP, header function can be used to redirect to a page in PHP and exit function is
called after header to ensure that code below does not get executed when we
redirect. E.g.
<?php header("Location: http://www.example.com/"); /* Redirect browser */ exit; ?>

see more

Q. How can a session variable be defined in one PHP file and transferred to another PHP
file? Can multiple PHP files share the same set of session variables and be in the same
session?

A session creates a file in a temporary directory on the server where


registered session variables and their values are stored.

This data will be available to all pages on the site during that visit. The
location of the temporary file is determined by a setting in the PHP.ini file
called session.save_path.

When a PHP script wants to retrieve the value from a session variable, PHP
automatically gets the unique session identifier string from the PHPSESSID
cookie and then looks in its temporary directory for the file bearing that name
and a validation can be done by comparing both values.

session_start() : A PHP session is easily started by making a call to the


session_start() function.This function first checks if a session is already
started and if none is started then it starts one.
Session variables are stored in associative array called $_SESSION[]. These
variables can be accessed during lifetime of a session. Yes multiple files can
access the same set of session variables by initializing session_start()
function at start of file.

see more

Q. Can you explain me in simple terms the use of the isset() function?

isset() function is used to check if the variable is set with some value. For example:
if(isset(($_POST['form-username'])) { //run the script in brackets }

The example here means if the field "username" in the form is set to some
value then only run the script in brackets.

If the field is not set with some value and is empty then skip running the
script.

Isset is usually used to check if user has entered some value to the
variable/field in the form.

see more

Q. Can isset() function be used to redirect php page to another php page?

The isset() function is used when there are functions to be performed if any input
type is set. We always use isset with loops. E.g.
if(isset($_POST['submit']){ -- code --}.

It cannot redirect php pages to another but can be used as a condition to redirect.
E.g.
if(isset($_POST['submit']){ header('location:home.php'); exit; }

This code will redirect the web page if the submit button is set to home.php page.

see more

Q. In HTML forms, what's the difference between using the GET method versus POST?
Practically when should we use POST and GET?

The basic difference in using GET and POST method is the security.
GET method will send the variables through a URL which is visible to users
and can be manipulated. POST method will send the values from one page to
another in a hidden way and this is not visible to users.

You should use POST when you are using forms in your web page, i.e inserting
the values in the database. POST method is the best method in that case.

GET should be used for searching purposes. E.g. whenever you search
something on Google, the values you have entered in the search box is
visible in the URL of the web page. i.e these queries don't change any values
in the database, they just fetch the values. So GET method should be used.

Moreover you cannot bookmark the URL if you are using POST request but it
is possible using GET method. Suppose you find awesome search result at
Google for some word and want to save that link. You will only be able to save
if they are using GET method otherwise you have to type the word again and
then get search result, you cannot directly jump to the link if it is not passing
value as GET method.

see more

View more

Ask your doubts to the instructor personally if they are not already answered on forum.

Next live chat: Today (7:00 - 8:00 PM)

For any queries, please write to us at vtc-support@internshala.com


Copyright 2016 Internshala

Potrebbero piacerti anche