PHP Basic

PHP (Hypertext Preprocessor) is a popular server-side scripting language for web development. It is widely used for creating dynamic web pages and web applications.

Features of PHP

  • Simple and easy to learn.
  • Open-source and free.
  • Platform-independent.
  • Supports various databases.
  • Extensive community support.

Embedding PHP Code in Web Pages

PHP code can be embedded directly into HTML files to create dynamic web pages. PHP scripts are enclosed within special tags, typically for the closing tag. Here's an example of embedding PHP code to display the current date and time:

<html>
<head>
<title> how to embed php </title>
</head>
<body>
        <?php
            # add php in any where in .html either .php
            echo " welcome in PHP ";
        ?>
</body>
</html>
welcome in PHP

Statement in PHP

we have to method to print statement in phpt once echo other is print but main difference to each other print return 1 after write and echo return null secondary difference is echo faster than print.

<?php
    echo "i am faster and void return <br>";
    print "i am return 1 after print";
?>
i am faster and void return
i am return 1 after print

Variable & Tokens

PHP code consists of various tokens, including keywords, identifiers, constants, strings, and operators. These tokens are the building blocks of PHP scripts.

Variables in PHP are used to store data. They start with a dollar sign ($) followed by an identifier. PHP variables are case-sensitive.

PHP Scope

  • Local scope: Variables declared within a function.
  • Global scope: Variables declared outside functions.
  • Static scope: Variables within a function that retain their values between function calls.
<?php
    $n1 = 1;
    $n2 = 2;
    echo "sum of ${$n1} and ${n2} is ${$n1+$n2}";
?>
sum of 1 and 2 is 3

Datatype

In PHP, data types specify the type of data that can be stored in a variable. PHP supports several data types, each designed for handling specific types of information. Here are some of the most common data types in PHP:

<?php
$number_data = 1;
$float_data = 0.5;
$boolean_data = true;
$char_data = '@';
$string_data = " write line in side ";
$void_data = null;
echo  "number {$number_data} float {$float_data} boolean {boolean_data} charactor {$char_data} string {$string_data} null {$void_data} ";
?>
number 1 float 0.5 boolean tyre charactor @ string write line in side null undefined

Constant

In PHP, a constant is a alu that cannot be changed once it is defined during a script's execution. Constatnt are typically used to store values that remain the same throughout the script and have specific, predefined purpose. we have to two way to define constant

  • const it is keyword that we are use write before variable
  • define it is function that inside we are pass constant variable and value
<?php
    define("PI",3.14159);
    const $user = "MayankDevil";
    echo "pi value is ".PI." name ".$user;
?>
pi value is 3.12159 name Mayank

Operation

calculater program using

arithemetic operator
and
switch statement
<?php
    # calculator.php : enter default number and calculate
    $n1 = 4;
    $n2 = 2;
    $n = 0;
    $choice = 3;
    switch ($choice)
    {
        case 1 : $n = $n1 + $n2; break;
        case 2 : $n = $n1 - $n2; break;
        case 3 : $n = $n1 * $n2; break;
        case 4 : $n = $n1 / $n2; break;
        case 5 : $n = $n1 % $n2; break;
        default : $n = "enter choice between [1 to 5]";
    }
    echo (" output : ".$n);
?>
output : 8

find even else odd between 100 number using

for loop
and
if else statement
<?php
    # find odd or even number between 0 to 100 number
    $n = 100;
    for ($i = 1; $i < $n; $i++)
    {
        if ($i % 2 == 0)
        {
            echo ("<div< number ".$i." is even </div<");
        }
        else
        {
            echo ("<div< number ".$i." is odd </div<");
        }
    }
?>
number 1 is odd
number 2 is even
number 3 is odd
...
number 100 is even

factorial find program using

dowhile loop
and
assignment operator
<?php
    # factorial.php :
    $n = 3;
    $f = 1;
    $i = 1;
    do
    {
        $f = $i * $f;
        $i++
    }
    while($i <= $n); 
    echo ("factorial of ".$n." is ".$f);
?>
factorial of 3 is 6

find number is prime or not using

while loop
and
if statement
<?php
    # primeNumber.php : fnd the number is prime or not
    $n = 11;
    $is_prime =  true;
    $i = 2;
    while ($i < $n)
    {
        if ($n % $i == 0) $is_prime = false;
        $i++;
    }
    if ($is_prime) echo(" prime "); else echo(" not prime ");
?>
prime

Functions

A function is a block of code that perfoms a specific task or set of tasks.Functions are a fundamental part of PHP programming and help you organize your code, make it more modular, and enable you to reuse code segments.

Simple Function

<?php
    # functions.php : function is set of code inside the named block
	function destoryWorld()
	{
		echo ("<div> welcome reuse the code </div>");
	}
	destoryWorld();
	destoryWorld();
?>
welcome reuse the code
welcome resuse the code

Parameter Function

<?php
    # the function take argument at call time that called parameterfunction
    function hello($name)
    {
        echo ("<div> welcome ".$name."</div>");
    }
    hello("Mayank");
    hello("PHPuser");
?>
welcome Mayank
welcome PHPuser

Return Funtion

<?php
    # a function that use return keyword to return value are called returnfunction
    function plus($n1, $n2)
    {
        return ($n1 + $n2);
    }
	echo(" sum of number function return ".plus(1,3));
	echo(" sum of number function return ".plus(5,3));
?>
sum of number function return 4
sum of number function return 8

Arrow Function

Array

In php array is list of element.The keys of the indexed array are integers that start at 0. Typically, you use indexed arrays when you want to access the elements by their positions.

<?php
    # array list of element
    $set = [9,2,11,400,20];
    # call by index
    echo " index1 ".$set[1]."<br>";
    echo " index0 ".$set[0]."<br>";
    echo " index4 ".$set[4]."<br>";
?>
index1 2
index0 9
index4 20

Indexed Array

<?php
    $cartoon = array("ironman","spiderman","batman","superman");
    foreach ($cartoon as $element)
    {
        echo "".$element."<br>";
    }
?>
ironman
spiderman
batman
superman

The

Associative
Array
<?php
$globe =
[
    'Japan' => 'Tokyo',
    'France' => 'Paris',
    'Germany' => 'Berlin'
];
foreach ($globe as $country => $capital)
{
    echo "".$country." = ".$capital."<br>";
}
?>
Japan = Tokyo
France = Paris
Germany = Berlin

The

MultiDimensional
Array
<?php
    $tasks = [
        ['Learn PHP programming', 2],
        ['Practice PHP', 2],
        ['Work', 8],
        ['Do exercise', 1],
    ];
    foreach ($tasks as $task) {
        foreach ($task as $task_detail) {
            echo "".$task_detail."<br>";
        }
    }
?>
Learn PHP programming
2
Practice PHP
2
Work
8
Do exercise
1

Array

sort()
or
array_reverse()
<?php
# sort() inbuild function to short array
# print_r() print all array 
$numbers = [9,2,11,400,20];
print_r(sort($numbers));
echo "<br>";
print_r(array_reverse($numbers))
?>
Array
(
[0] => 2
[1] => 9
[2] => 11
[3] => 20
[4] => 400
)
Array
(
[0] => 400
[1] => 20
[2] => 11
[3] => 9
[4] => 2
)

Array function {

current()
|
next()
|
prev()
|
end()
}
<?php
$a = Array(2,5,4,3,1);
echo "<div>  current() element ".current($a)."</div>";
next($a);
next($a);
echo "<div>  after next() element ".current($a)."</div>";
prev($a);
echo "<div>  after prev() ious element ".current($a)."</div>";
echo "<div>  end() element ".end($a)."</div>";
?>
current() element 2
after next() element 4
after pre() ious element 5
end() element 1

Two

array_combine()
and
array_slice()
<?php
$a = Array(1,2,4);
$b = Array(5,6);
$c = array_combine($a,$b);
foreach($c as $element) echo $element;
echo "<br>";
$d = array_slice($c,2);
foreach($d as $element) echo $element;
?>
12456
654

String

A string in PHP is a sequence of characters,like words or sentences. You can work with string to store and manipulate text, PHP offers various functions to perform tasks like finding text, changing text, and measuring the length of strings.Strings are a fundamental part of web development for things like displaying messages, processing forms, and working with data.

Declare string in PHP or find

strlen()
|
strtoupper()
|
strtolower()
<?php
$s = "Welcome PHP";
echo strlen($s);
echo strtoupper($s);
echo strtolower($s);
?>
11WELCOME PHPwelcome php

How to string

str_replace()
|
substr()
|
trim()
<?php
$s = "Welcome PHP";
echo str_replace("PHP","Mayank",$s);
echo substr($s,3,4);
echo trim($s);
?>
Welcome MayankcomeWelcome PHP

Find

strpos()
and how to
strrev()
and
str_repeat()
<?php
$s = "Welcome PHP";
echo strpos($s,"come");
echo strrev($s);
echo str_repeat($s,3);
?>
3PHP emocleWWelcome PHPWelcome PHPWelcome PHP

Math

Math in PHP involves performing numberical calculations. You can use PHP for tasks like arithemetic functional and more. PHP provides functions for comman math operations, making it used for financial calulations, data processing, and much more in web development.

<?php
echo round(0.5)."<br>";
echo ceil(3.5)."<br>";
echo floor(3.5)."<br>";
echo abs(0.5)."<br>";
echo pow(2,3)."<br>";
echo sqrt(16)."<br>";
echo max(1,4,6)."<br>";
echo min(1,3,2)."<br>";
echo rand(1,10)."<br>";
echo log(16,2)."<br>";
echo pi()."<br>";
?>
1
4
3
0.5
8
4
6
1
1
4
3.1415926535898

Cookies

In PHP, cookies are small pieces of data stored on a user's web browser. They are often used to remember information about user, like login status of user preferences. Cookies help websites provide personalized experience and keep track of user interactions.

[

login.php
] : onSubmit SETCOOKIE and goto welcome
<!DOCTYPE html>
<html lang="en">
<head>
    <title>cookies protocol</title>
</head>
<body>
    <form>
        <div>
            <label for="username"> Enter Username : </label>
            <input type="text" name="username" id="username">
        </div>
        <div>
            <label for="password"> Enter Password : </label>
            <input type="password" name="password" id="password">
        </div>

        <div>
            <input type="submit" value="Login" name="submit">
        </div>
    </form>
    <?php
        if (isset($_REQUEST['submit']))
        {
            setcookie("CODE",$_REQUEST['password'],time() + (60*60));

            /*setcookie( string $name [, string $value = "" [, int $expires = 0 [, string $path = "" [, string $domain = "" [, bool $secure [, bool $httponly [, array $options = [] ]]]]]]])*/ 

            header("location:welcome.php"); // redirect to welcome
        }
    ?>
</body>
</html>

[

welcome.php
] : if COOKIE_NOT_FOUND goto Login else welcome
<?php
    if ($_COOKIE['CODE'] != "open")
    {
        header("location:cookies.php");
    }
    else
    {
        echo " <h1> Welcome to Dashboard </h1>";
    }
?>

Sessions

A PHP session is a temporay storage for data that can be used across multiple pages on a website to remember user information.

The

$_SESSION
function
session_start()
,
session_reset()
and
session_destroy()
use.
<?php
    session_start();
    if (isset($_REQUEST['reset'])) {
        session_reset();
    }
    if (isset($_REQUEST['destory'])) {
        session_destroy();
        session_start();
    }
    if (isset($_REQUEST['username']))
    {
        $_SESSION['username'] = $_REQUEST['username'];
    }
    $username = isset($_SESSION['username'])? $_SESSION['username'] : 'MasterMayank';
?>
<html lang="en">
<head>
    <title> MayankDevil </title>
</head>
<body>
    <h1> Welcome, <?php echo $username; ?>! </h1>   
    <form action="<?php $_SERVER['PHP_SELF'] ?>" method="post">
        <div>
            <label for="username"> Enter Username =  </label>
            <input type="text" name="username" id="username">
        </div>
        <div>
            <input type="submit" name="submit" value="Submit">
            <input type="submit" name="reset" value="Reset">
            <input type="submit" value="destory" id="destory">
        </div>
    </form>
</body>
</html>

form

Form handling is gather and process user input by url. Every form data is fetch with url of web browser and php form handling work on it. PHP use supe vairable like { $_GET[] , $_POST[] , $_REQUEST[] } to fetch user input data on url by the help of name value.

Get Form field data using

$_REQUEST[]
and
$_SERVER[]
<html lang="en">
<title>get form values</title>
</head>
<body>
    <form action="<?php $_SERVER['PHP_SELF'] ?>" >

        <div>
            <label for="username"> Enter Username : </label>
            <input type="text" name="username" id="username">
        </div>
        <div>
            <label for="number"> Enter Number : </label>
            <input type="tel" name="number" id="number">
        </div>
        <div>
            <label for="mail"> Enter Email-Id : </label>
            <input type="email" name="email" id="mail">
        </div>
        <div>
            <label for="password"> Enter Password : </label>
            <input type="password" name="password" id="password">
        </div>
        <div>
            <input type="submit" value="Login" name="submit">
        </div>
    </form>
    <?php
        if (isset($_REQUEST['submit']))
        {
            echo "<div>".$_REQUEST['username']."</div>";
            echo "<div>".$_REQUEST['number']."</div>";
            echo "<div>".$_REQUEST['email']."</div>";
            echo "<div>".$_REQUEST['password']."</div>";
        }
    ?>
</body>
</html>

Get Form checkbox data

<html lang="en">
<head>
<title>get form values</title>
</head>
<body>
    <form action="<?php $_SERVER['PHP_SELF']?>">
        <label for="">
            <input type="checkbox" name="color[]" value="red"> red
        </label>
        <label for="">
            <input type="checkbox" name="color[]" value="yellow"> yellow
        </label>
        <label for="">
            <input type="checkbox" name="color[]" value="green"> green
        </label>
        <label for="">
            <input type="checkbox" name="color[]" value="blue"> blue
        </label>
        <div>
            <input type="submit" value="Login" name="submit">
        </div>
    </form>
    <?php
        if (isset($_REQUEST['submit']))
        {
            $name = $_GET['color'];

            foreach ($name as $color)
            { 
                echo "<div>".$color."</div>";
            }
        }
    ?>
</body>
</html>

Database Connection

PHP is widely famous script to connect database because it connection web to database is much simple to all

  1. Establise Connection
  2. Execute Query
  3. Close Connection

PHP Database

mysqli_connect() mysqli_connect_errno() mysqli_connect_error()
<?php
$connection = mysqli_connect("localhosts","root","","vip");
/*
    mysqli_connect() : function return connection true
    take arguments :-
        1 : hostname {x}
        2 : username {x}
        3 : password
        4 : database
*/ 
if ($connection)
{
    echo (" connection successfully ");
}
else
{
    die (mysqli_connect_errno()." connection error : ".mysqli_connect_error());
}
?>
connection successfully

How to execute

mysqli_query()
or
require()
connection
<?php
    require('connection.php');
    /*
        mysqli_query(); : function return response of mysqli 
        take arguments :-
            1 :  connection     {x}
            2 :  query          {x}
    */
    $query = "insert into onam values(2)";
    $result = mysqli_query($connection,$query);

?>

PHP Connection

include()
and
mysqli_close()
<?php
    include('connection.php');
    /*
        mysqli_close : function return ture false of connection cut
        take argument :-
            1 : connection  {x}
    */
    if (mysqli_close($connection))
    {
        echo (" connection closed ");
    } 
?>
connection closed

File Handling

PHP file handling is the process of working with files in PHP, it involes operations like opening, reading, writing, appeneding and closing files.

File Handling in PHP to

create write append close
file
<?php
    // Open a file for writing (creates a new file if it doen't exist or truncates an existing file)
    $file = fopen("example.txt","w");
    if ($file) 
    {
        // Write some content to the file
        fwrite($file,"if you are like follow me on github.com ");"
        fclose($file);  // Close the file
        $file = fopen("example.txt","a");   // Open the file for appending
        if ($file) 
        {
            // Append more content to the file
            fwrite($file," https://github.com/MayankDevil/");
            fclose($file);  // Close the file
            // Open the file for reading
            $file = fopen("example.txt","r");
            if ($file) 
            {
                while (!feof($file)) 
                {
                    echo fgets($file);  // Read and display the content of the file
                }
            }
            fclose($file);  // Close the file
        }
        else
        {
            echo "Failed to open the file for reading.";
        }
    }
    else
    {
        echo "Failed to open the file for writing.";
    }
?>
?>
if you are like follow me on github.com https://github.com/MayankDevil/

PHP_CRUD

PHP CRUD is very large project that not possible to visit code here you are see to click below button

View PHP_CRUD
Procoder © Designed | Developed by Mayank