Introduction to PHP

Posted by fallen00sniper on Wed, 02 Mar 2022 05:46:28 +0100

Foundation (unimportant)

content

  • PHP environment installation
  • Variables and constants
  • Common operators
  • Conditional branch statement
  • Circular statement
  • array
  • function
  • Database operation

What is PHP?

  • PHP ("PHP: Hypertext Preprocessor", acronym for hypertext preprocessor) is a widely used open source multi-purpose scripting language, which can be embedded into HTML, especially suitable for web development
  • 1994 "Personal Home Page Tool"

What can PHP do?

  • Server script
  • Command line script
  • Writing desktop applications
  • https://w3techs.com/ 78.9% of websites use PHP

PHP and its functions

  • Run on the server side
  • Cross platform
  • scripting language
  • free

First PHP program

<?php
echo "Hello world"; 
?>

echo statement

  • echo is the output statement in PHP
  • Used to output a string (the string is enclosed in double quotes)
  • Note that there must be at least one space between the echo keyword and the string

PHP evaluation expression

<?php
echo 3 * 3; 
?>

PHP string

<?php
echo 'Hi,' . 'PHP!'; 
?>
  • A string is a word or a sentence enclosed in double or single quotation marks
  • Connector (.) Connection can connect two characters with

PHP statement Terminator

  • There will be a semicolon at the end of each PHP code line;
  • be careful:
    • In PHP programming, you need to add a semicolon at the end of each statement;
    • Semicolon; It must be entered in English format or half angle state

notes

<?php
//Enter hello world
echo 'hello world! ';
/*
* Multi line comments, output hello PHP!
*/
echo 'hello PHP ! ';
?>

PHP environment installation

Construction of PHP environment

  • Windows: phpstudy / pagoda, etc
  • Linux
    • Install Apache
sudo apt-get install apache2 -y
  • Install PHP
sudo apt-get install php -y

variable

What are variables?

<?php
$var = 'Apple'; 
echo $var; 
$var = 'Banana'; 
echo $var; 
?>
  • Variables are "containers" for storing information

How to define variables?

<?php
$var_name = "Apple"; 
$n = 10; 
?>
  • PHP has no command to declare variables
  • A variable is created the first time it is assigned a value

Naming rules for variable names

  • The variable starts with the $sign, followed by the name of the variable
  • Variable names must be alphabetic or underlined "" start
  • Variable names can only consist of letters, numbers, and "" It can also contain Chinese characters
  • Variable names cannot contain spaces
  • Variable names are case sensitive

Data type of variable

  • String (string)
  • Integer (integer)
  • Float (floating point)
  • Boolean (Boolean)
  • Array
  • Object
  • NULL (NULL)

character string

<?php
$x = "Hello world !";
$y = 'Hello world ! ';
$z = "Say: \"Hello world!\",";
$a= <<<EOF
"abc"$y
"123"
EOF;
// A separate line is required at the end and no space is allowed before and after it
echo $a;
?>

integer

<?php
$x = 5985; 
var_dump($x); 
$x = -345; // negative 
var_dump($x); 
$x = 0x8C; // Hexadecimal number 
var_dump($x); 
$x = 047; // Octal number 
var_dump($x); 
?>

float

<?php
$x = 10.365;
var_dump($x);
echo "<br>";
$x = 2.4e3;
var_dump($x);
echo "<br>";
$x = 8E-5;
var_dump($x);
?>

Boolean type

<?php
$flag = true; 
$flag = false; 
$flag = TRUE; 
$flag = FALSE; 
?>

array

<?php
$cars = array("Volvo", "BMW", "Toyota"); 
var_dump($cars); 
?>

object

<?php
class Car{
public $color;
function __construct($color="green") {
$this->color = $color;
}
}
$car = new Car("red");
echo "Car color is " . $car->color;
var_dump($car);
?>

NULL value

<?php
$x="Hello world!"; 
$x=null; 
var_dump($x); 
?>

constant

What is a constant?

  • A constant is an identifier of a simple value
  • This value cannot be changed in the script
  • A constant consists of English letters, underscores, and numbers, but numbers cannot appear as initials
  • Constants can be used throughout the script

Define constants

<?php
// Case sensitive constant names 
define("GREETING", "Hello world"); 
echo GREETING; // Output "Hello world" 
echo '<br>'; 
echo greeting; // Output "greeting" 
?>

Constant value

<?php
define("PI", 3.14);
$r=1;
//Get constants directly using constant names
$area = PI * $r * $r;
//Get constant through constant function
$area = constant("PI") * $r * $r;
?>

How to determine whether constants are defined

<?php
define("PI1", 3.14); 
$is = defined("PI"); 
var_dump($is); 
?>

magic constant

  • __ LINE__ Current line number in the file
  • __ FILE__ The full path and file name of the file. If used in a contained file, returns the name of the contained file
  • __ DIR__ The directory where the file is located. If it is used in an included file, the directory where the included file is located is returned
  • __ FUNCTION__ Function name__ CLASS__ Class name__ TRAIT__ Trail's name__ METHOD__ Class's method name (case sensitive)__ NAMESPACE__ Name of the current namespace (case sensitive)

Common operators

What are operators?

  • Operators are identifiers that tell PHP to perform related operations
  • What are the operators
  • Arithmetic operator
  • Assignment Operators
  • Comparison operator
  • Ternary operator
  • Logical operator
  • String Concatenation Operators
  • Error control operator

Arithmetic operator

operator

name

describe

example

result

x + y

plus

Sum of x and y

2 + 2

4

x - y

reduce

Difference between x and y

5 - 2

3

x * y

ride

Product of x and y

5 * 2

10

x / y

except

Quotient of x and y

15 / 5

3

x % y

Modulus (remainder of division)

The remainder of x divided by y

5 % 2 10 % 8 10 % 2

1 2 0

- x

Reverse

x inversion

-2

a . b

Juxtaposition

Connect two strings

"Hi" . "Ha"

HiHa

Assignment Operators

operator

Equivalent to

describe

x = y

x = y

The left operand is set to the value of the right expression

x += y

x = x + y

plus

x - = y

x = x - y

reduce

x *= y

x = x * y

ride

x /= y

x = x /

y

except

x %= y

x = x %

y

Modulus (remainder of division)

a . = b

a = a . b

Connect two strings

Comparison operator

operator

name

describe

example

x == y

be equal to

Returns true if x equals y

5 = = 8 returns false

x === y

Absolutely equal to

Returns true if x equals y and they are of the same type

5 = = = "5" returns false

x != y

Not equal to

Returns true if x is not equal to y

5!= 8 return true

x <> y

Not equal to

Returns true if x is not equal to y

5 < > 8 returns true

x !== y

Absolutely not equal to

Returns true if x is not equal to y, or if they are of different types

5!== "5" returns true

x > y

greater than

Returns true if x is greater than y

5> 8 return false

x < y

less than

Returns true if x is less than y

5 < 8 returns true

x >= y

Greater than or equal to

Returns true if x is greater than or equal to y

5> = 8 returns false

x <= y

Less than or equal to

Returns true if x is less than or equal to y

5 < = 8 returns true

Ternary operator

<?php
$msg = $a >= 60 ? "pass": "fail,"; 
echo $msg; 
?>

Logical operator

operator

name

describe

example

x and y

And

Returns true if both x and y are true

x=6 y=3 (x < 10 and Y > 1) returns true

x or y

or

Returns true if at least one of x and y is true

x=6 y=3 (x==6 or y==5) return true

x xor y Difference is true The same is false

XOR

Returns true if only one of x and y is true

x=6 y=3 (x==6 xor y==3) return false

x && y

And

Returns true if both x and y are true

x=6 y=3 (x < 10 & & Y > 1) return true

x || y

or

Returns true if at least one of x and y is true

x=6 y=3 (x = = 5 | y = = 5) return false

! x

wrong

Returns true if x is not true

x=6 y=3 ! (x==y) returns true

Error control operator

  • Error control operator '@'
    • Any error messages that may be generated by the expression are ignored

Arithmetic operation function

<?php
$maxLine = 4; //Number of people in each row
$no = 17;//Student number
$line = ceil($no / $maxLine);
$row = $no % $maxLine ? ($no % $maxLine) :
$maxLine;
echo "NO: " . $no . PHP_EOL;
echo "Line: " . $line . PHP_EOL;
echo "Row: " . $row . PHP_EOL;
?>

Conditional branch statement

PHP conditional statement

  • if statement
  • if...else statement
  • if...elseif....else statement
  • switch statement

if statement

<?php
$score = 78; 
if ($score > 80) 
{ 
echo "Good!"; 
} 
?>

if...else statement

<?php
$score = 78;
if ($score > 80)
{
echo "Good !";
}
else
{
echo "Not good !";
}
?>

if...elseif....else statement

<?php
$score = 78;
if ($score > 80){
echo "Very good !";
}else if($score > 60){
echo "good !";
}else{
echo "Bad !";
}
?>

Switch statement

<?php
$favcolor="red";
switch ($favcolor){
case "red":
echo "My favorite color is red!"; break;
case "blue":
echo "My favorite color is blue!"; break;
case "green":
echo "My favorite color is green!"; break;
default:
echo "My favorite color is not red , blue , Or green!";
}
?>

Circular statement

PHP loop

When writing code, it is often necessary to make the same code block run again and again. You can use circular statements in the code to complete this task

  • While
  • do...while
  • for
  • foreach

while loop

<?php
$n = 1;
$sum = 0;
while($n <=100){
$sum += $n;
$n++;
}
echo "sum: ". $sum;
?>

do...while loop

<?php
$n = 1;
$sum = 0;
do{
$sum += $n;
$n++;
}while($n <= 100);
echo "sum: ". $sum;
?>

for loop

<?php
$sum = 0; 
for ($i = 1; $i <= 100; $i++){ 
$sum += $i; 
}
echo "sum: ". $sum; 
?>

array

What is an array?

  • A language structure consisting of a key value pair
  • PHP has three types of arrays
    • Index array
    • Associative array
    • Multidimensional array

Create array

<?php
//Index array
$cars=array("Volvo", "BMW", "Toyota");
//Associative array
$age=array(
"Peter" => 35,
"Ben" => 37,
"Joe" => 43
);
?>

Accessing and modifying array values

<?php
//Index array
$cars = array("Volvo", "BMW", "Toyota");
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
echo "I love " . $cars[1];
$age = array("Peter"=> 35, "Ben" => 37);
$age[ 'Peter '] = 18;
echo "Peter is " . $age[ 'Peter '];
?>

for loop traversal array

<?php
$fruit=array('Apple','Banana','Cherry'); 
for($i=0; $i<3; $i++){ 
echo 'Fruit Array['.$i.'] ='. $fruit[$i]; 
} 
?>

foreach loop traverses array

<?php
$fruit=array('Apple','Banana','Cherry'); 
foreach($fruit as $key => $value){ 
echo 'Fruit Array['.$key.'] ='. $value; 
} 
?>

Function introduction

What is a function?

  • Functions are named, and each function has a unique name
  • Functions are independent and can perform their own tasks without the intervention of other parts of the program
  • Functions perform specific tasks
  • Function can return a return value to the program calling it

Find the maximum value in the array?

<?php
$array = array(35, 23, 41, 652, 53, 42, 15);
$max = $array[0];
foreach($array as $num){
if($num > $max)
$max = $num;
}
echo $max;
?>

Why use functions?

  • Improve program reusability
  • Improve software maintainability
  • Improve software development efficiency
  • Improve software reliability
  • Complexity of control program design

Classification of functions

  • Built in function
    • There are more than 1000 standard functions in the standard PHP distribution package. These standard functions are built-in in the system and can be used directly without users creating them themselves.
  • Custom function
    • User created and defined functions

Structure of function

Basic composition of a function

<?php
function add($a, $b){
$sum = $a + $b;
return $sum;
}
$s = add(3, 5);
echo $s;
?>

Basic composition of a function

  • Keyword (function)
  • Function name
  • Function parameters
  • Function body
  • Return value

Function naming

  • The function name cannot be the same as the existing function name
  • Function names can only contain letters, numbers, and underscores
  • Function names cannot start with numbers

Function parameters

  • The parameter is specified in a bracket after the function name
  • It is mainly to add more functions to functions, similar to variables

Return value

  • return statement
  • Let the function return a value
  • You can return any type including arrays and objects
  • The return statement immediately aborts the function and returns control to the line of code calling the function

Define a function

<?php
function ArrayMaxValue($array){
$max = $array[0];
foreach($array as $num){
if($num >
$max
}
return $max;
$max)
= $num;
}
$array1 = array(35, 23, 41, 652, 53, 42, 15);
$array1MaxValue = ArrayMaxValue($array1);
echo $array1MaxValue;
?>

Characteristics of function

Formal and argument

  • An argument is a parameter when a function is called
  • Formal parameters are parameters when a function is declared

Formal parameter and argument

<?php
function add($a, $b){
$tmp = $a + $b;
return $tmp;
}
$sum = add(3, 5);
echo $sum;
?>

Default value of parameter

<?php
function add($a, $b = 0){
$tmp = $a + $b;
return $tmp;
}
$sum = add(3, 5);
echo $sum;
?>

Strongly typed parameter

  • Specifies the type for the parameter in the parameter list
  • If the incoming data types do not match, a TypeError exception will be thrown

Strongly typed parameter

<?php
declare(strict_types
function add(int $a,
$tmp = $a + $b;
return $tmp;
}
$sum = add(1.3, 5);
echo $sum;
= 1);
int $b){
?>

Database operation

Connect database

<?php 
$servername = "localhost"; 
$username = "root"; 
$password = "root"; 
// Create connection 
$conn = mysqli_connect($servername, $username, $password); 
// Detect connection 
if (!$conn) { 
die("Connection failed: " . mysqli_connect_error()); 
}
echo "success";?>

Create database

<?php 
$servername = "localhost"; 
$username = "root"; 
$password = "root"; 
// Create connection 
$conn = mysqli_connect($servername, $username, $password); 
// Detect connection 
if (!$conn) { 
die("connection failed: " . mysqli_connect_error()); 
}
// Create database 
$sql = "CREATE DATABASE PHPDB"; 
if (mysqli_query($conn, $sql)) { 
echo "success"; 
} else { 
echo "Error creating database: " . mysqli_error($conn); 
}
mysqli_close($conn);

Create data table

<?php 
$servername = "localhost"; 
$username = "root"; 
$password = "root"; 
$dbname = "PHPDB"; 
// Create connection 
$conn = new mysqli($servername, $username, $password, $dbname); 
// Detect connection 
if ($conn->connect_error) { 
die("connection failed: " . $conn->connect_error); 
}
// Create data table with sql 
$sql = "CREATE TABLE MyGuests ( 
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, 
firstname VARCHAR(30) NOT NULL, 
lastname VARCHAR(30) NOT NULL, 
email VARCHAR(50) 
)"; 
if ($conn->query($sql) === TRUE) { 
echo "Table MyGuests created successfully"; 
} else { 
echo "Error creating data table: " . $conn->error; 
}
$conn->close();

insert data

<?php 
$servername = "localhost"; 
$username = "root"; 
$password = "root"; 
$dbname = "PHPDB"; 
// Create connection 
$conn = mysqli_connect($servername, 
$username, $password, $dbname); 
// Detect connection 
if (!$conn) { 
die("Connection failed: " . 
mysqli_connect_error()); 
}
$sql = "INSERT INTO MyGuests (firstname, 
lastname, email) 
VALUES ('John', 'Doe', 
'john@example.com')"; 
if (mysqli_query($conn, $sql)) { 
echo "success"; 
} else { 
echo "Error: " . $sql . "<br>" . 
mysqli_error($conn); 
}
mysqli_close($conn);

OR

<?php 
$servername = "localhost"; 
$username = "root"; 
$password = "root"; 
$dbname = "PHPDB"; 
// Create connection 
$conn = mysqli_connect($servername, $username, $password, 
$dbname); 
// Detect connection 
if (!$conn) { 
die("Connection failed: " . mysqli_connect_error()); 
}
$sql .= "INSERT INTO MyGuests (firstname, lastname, email) 
VALUES ('Mary', 'Moe', 'mary@example.com');"; 
$sql .= "INSERT INTO MyGuests (firstname, lastname, email) 
VALUES ('Julie', 'Dooley', 'julie@example.com')"; 
if (mysqli_multi_query($conn, $sql)) { 
echo "success"; 
} else { 
echo "Error: " . $sql . "<br>" . mysqli_error($conn); 
}
mysqli_close($conn);

Query data

<?php 
$servername = "localhost"; 
$username = "root"; 
$password = "root"; 
$dbname = "PHPDB"; 
// Create connection 
$conn = mysqli_connect($servername, $username, $password, $dbname); 
// Detect connection 
if (!$conn) { 
die("Connection failed: " . mysqli_connect_error()); 
}
$sql = "SELECT id, firstname, lastname FROM MyGuests"; 
$result = mysqli_query($conn, $sql); 
if (mysqli_num_rows($result) > 0) { 
// output data 
while($row = mysqli_fetch_assoc($result)) { 
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . 
$row["lastname"]. PHP_EOL; 
} 
} else { 
echo "No result!"; 
}
mysqli_close($conn);

Update data

<?php 
$servername = "localhost"; 
$username = "root"; 
$password = "root"; 
$dbname = "PHPDB"; 
// Create connection 
$conn = mysqli_connect($servername, $username, $password, $dbname); 
// Detect connection 
if (!$conn) { 
die("Connection failed: " . mysqli_connect_error()); 
}
$result = mysqli_query($conn,"SELECT * FROM myguests ORDER BY id"); 
while($row = mysqli_fetch_array($result)) 
{ 
echo $row['firstname']; 
echo " " . $row['lastname']; 
echo " " . $row['email']; 
echo "<br>"; 
}
mysqli_close($conn);

Delete data

<?php 
$conn=mysqli_connect("localhost","root","root","PHPDB"); 
// Detect connection 
if (mysqli_connect_errno()) 
{ 
echo "connection failed: " . mysqli_connect_error(); 
}
mysqli_query($conn,"UPDATE myguests SET 
firstname='Test' WHERE id = 2"); 
mysqli_close($conn);