plain PHP

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

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. The example below shows how to use the super global variable $GLOBALS:

PHP $_SERVER

$_SERVER is a PHP super global variable which holds information about headers, paths, and script locations. The example below shows how to use some of the elements in $_SERVER:

here is a URL: homepage/attendance/success.php? what does the "?" indicate?

? indicates a get method in form control/submission context

PHP syntax

A PHP script starts with: <?php and ends with ?>

Self keyword

A class can have both static and non-static methods. A static method can be accessed from a method in the same class using the self keyword and double colon (::):

PHP constructor

A constructor allows you to initialize an object's properties upon creation of the object. If you create a __construct() function, PHP will automatically call this function when you create an object from a class. Notice that the construct function starts with two underscores (__)! We see in the example below, that using a constructor saves us from calling the set_name() method which reduces the amount of code

PHP cookies

A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values. A cookie is created with the setcookie() function. setcookie(name, value, expire, path, domain, secure, httponly);

PHP Sessions

A session is a way to store information (in variables) to be used across multiple pages. Unlike a cookie, the information is not stored on the users computer. When you work with an application, you open it, do some changes, and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are or what you do, because the HTTP address doesn't maintain state. Session variables solve this problem by storing user information to be used across multiple pages (e.g. username, favorite color, etc). By default, session variables last until the user closes the browser. So; Session variables hold information about one single user, and are available to all pages in one application.

Ajax

AJAX (Asynchronous JavaScript and XML) is a technique used in web development to send and receive data from a server without requiring the entire web page to be reloaded. It allows for asynchronous communication between a web browser and a server, enabling dynamic and responsive web applications.

InnoDB

Absolutley make sure that the storage engine is innoDB, otherwise you cant really make fK constraints in phpmyadmin(gives access to relational view) each table has to be switched to innoDB. adding a FK is confusing as **** in this GUI. in this screenshot I selected the "attendee" table , gave the constraint a descriptive name, stated what column in attendee would be the FK, then said what db, table and column to reference to

abstract classes and methods

Abstract classes and methods are when the parent class has a named method, but need its child class(es) to fill out the tasks. An abstract class is a class that contains at least one abstract method. An abstract method is a method that is declared, but not implemented in the code. An abstract class or method is defined with the abstract When inheriting from an abstract class, the child class method must be defined with the same name, and the same or a less restricted access modifier. So, if the abstract method is defined as protected, the child class method must be defined as either protected or public, but not private. Also, the type and number of required arguments must be the same. However, the child classes may have optional arguments in addition. So, when a child class is inherited from an abstract class, we have the following rules: The child class method must be defined with the same name and it redeclares the parent abstract method The child class method must be defined with the same or a less restricted access modifier The number of required arguments must be the same. However, the child class may have optional arguments in addition

Try Catch Block

An exception handling process in programming where possible error generating situations are smoothly handled during execution, with the situation is enclosed inside the try section, and one or more catches are built in to handle the possible errors that may occur. This is a key feature in making very large programs robust and error free.

Associative Arrays

Associative arrays are arrays that use named keys that you assign to them. There are two ways to create an associative array:

GET vs. POST

Both GET and POST create an array (e.g. array( key1 => value1, key2 => value2, key3 => value3, ...)). This array holds key/value pairs, where keys are the names of the form controls and values are the input data from the user. Both GET and POST are treated as $_GET and $_POST. These 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. $_GET is an array of variables passed to the current script via the URL parameters. $_POST is an array of variables passed to the current script via the HTTP POST method.

Variable Number of Arguments

By using the ... operator in front of the function parameter, the function accepts an unknown number of arguments. This is also called a variadic function. The variadic function argument becomes an array. You can only have one argument with variable length, and it has to be the last argument.

PHP Object

Classes and objects are the two main aspects of object-oriented programming. A class is a template for objects, and an object is an instance of a class. When the individual objects are created, they inherit all the properties and behaviors from the class, but each object will have different values for the properties. Let's assume we have a class named Car that can have properties like model, color, etc. We can define variables like $model, $color, and so on, to hold the values of these properties. When the individual objects (Volvo, BMW, Toyota, etc.) are created, they inherit all the properties and behaviors from the class, but each object will have different values for the properties. If you create a __construct() function, PHP will automatically call this function when you create an object from a class.

PHP constants

Constants are like variables, except that once they are defined they cannot be changed or undefined. A constant is an identifier (name) for a simple value. The value cannot be changed during the script. A valid constant name starts with a letter or underscore (no $ sign before the constant name). Note: Unlike variables, constants are automatically global across the entire script. Constants are automatically global and can be used across the entire script. To create a constant, use the define() function.

what is the conn.php file?

In PHP, a conn (connection) file is commonly used to establish a connection to a database. This file typically contains the configuration details required to connect to the database and initializes the connection using these details. Let's break down the key components and purpose of your provided conn file:

how to create a variable in PHP

In PHP, a variable starts with the $ sign, followed by the name of the variable. PHP is a loosely typed or dynamically typed language by default, which means that variable types are not explicitly declared, and PHP will attempt to automatically convert variable types as needed during runtime. PHP is loosely typed.

Passing Arguments by Reference

In PHP, arguments are usually passed by value, which means that a copy of the value is used in the function and the variable that was passed into the function cannot be changed. When a function argument is passed by reference, changes to the argument also change the variable that was passed in. To turn a function argument into a reference, the & operator is used:

PHP Case Sensitivity

In PHP, keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined functions are not case-sensitive.

what is "->" in php

In PHP, the -> operator is used to access properties and methods of an object. It's a key component of object-oriented programming in PHP. Here's a breakdown of how it works: Accessing Object Properties: You use -> to access a property of an object. For example, if you have an object $car of a class Car, and this class has a property color, you would access this property as $car->color. Calling Object Methods: Similarly, you use -> to call methods on an object. If Car class has a method getColor(), you would call it as $car->getColor()

variable scope

In PHP, variables can be declared anywhere in the script. The scope of a variable is the part of the script where the variable can be referenced/used. PHP has three different variable scopes: local global static A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function: A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function:

PHP Loops

In PHP, we have the following loop types: while - loops through a block of code as long as the specified condition is true do...while - loops through a block of code once, and then repeats the loop as long as the 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 is a Loosely Typed Language

In the examples above, notice that we did not have to tell PHP which data type the variable is. PHP automatically associates a data type to the variable, depending on its value. Since the data types are not set in a strict sense, you can do things like adding a string to an integer without causing an error. In PHP 7, type declarations were added. This gives us an option to specify the expected data type when declaring a function, and by adding the strict declaration, it will throw a "Fatal Error" if the data type mismatches. In the following example we try to send both a number and a string to the function without using strict:

Interfaces

Interfaces allow you to specify what methods a class should implement. Interfaces make it easy to use a variety of different classes in the same way. When one or more classes use the same interface, it is referred to as "polymorphism". Interfaces are declared with the interface keyword To implement an interface, a class must use the implements keyword. A class that implements an interface must implement all of the interface's methods.

Multi-line Comments

Multi-line comments start with /* and end with */.

NaN

NaN stands for Not a Number. NaN is used for impossible mathematical operations.

Namespaces

Namespaces are qualifiers that solve two different problems: They allow for better organization by grouping classes that work together to perform a task They allow the same name to be used for more than one class For example, you may have a set of classes which describe an HTML table, such as Table, Row and Cell while also having another set of classes to describe furniture, such as Table, Chair and Bed. Namespaces can be used to organize the classes into two different groups while also preventing the two classes Table and Table from being mixed up.

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. To do this, use the static keyword when you first declare the variable: Then, each time the function is called, that variable will still have the information it contained from the last time the function was called. Note: The variable is still local to the function.

null datatype

Null is a special data type which can have only one value: NULL. A variable of data type NULL is a variable that has no value assigned to it. Tip: If a variable is created without a value, it is automatically assigned a value of NULL. Variables can also be emptied by setting the value to NULL:

PHP $_GET

PHP $_GET is a PHP super global variable which is used to collect form data after submitting an HTML form with method="get". $_GET can also collect data sent in the URL. Assume we have an HTML page that contains a hyperlink with parameters:

PHP $_POST

PHP $_POST is a PHP super global variable which is used to collect form data after submitting an HTML form with method="post". $_POST is also widely used to pass variables. The example below shows a form with an input field and a submit button. When a user submits the data by clicking on "Submit", the form data is sent to the file specified in the action attribute of the <form> tag. In this example, we point to the file itself for processing form data. If you wish to use another PHP file to process form data, replace that with the filename of your choice. Then, we can use the super global variable $_POST to collect the value of the input field:

PHP $_REQUEST

PHP $_REQUEST is a PHP super global variable which is used to collect data after submitting an HTML form. The example below shows a form with an input field and a submit button. When a user submits the data by clicking on "Submit", the form data is sent to the file specified in the action attribute of the <form> tag. In this example, we point to this file itself for processing form data. If you wish to use another PHP file to process form data, replace that with the filename of your choice. Then, we can use the super global variable $_REQUEST to collect the value of the input field:

What Can PHP Do?

PHP can generate dynamic page content PHP can create, open, read, write, delete, and close files on the server PHP can collect form data PHP can send and receive cookies PHP can add, delete, modify data in your database PHP can be used to control user-access PHP can encrypt data

PHP file

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

PHP magic constants

PHP has nine predefined constants that change value depending on where they are used, and therefor they are called "magic constants". These magic constants are written with a double underscore at the start and the end, except for the ClassName::class constant.

What is PHP?

PHP is an acronym for "PHP: Hypertext Preprocessor" PHP is a widely-used, open source scripting language PHP scripts are executed on the server A PHP script is executed on the server, and the plain HTML result is sent back to the browser. A PHP script is executed on the server, and the plain HTML result is sent back to the browser.

PHP traits

PHP only supports single inheritance: a child class can inherit only from one single parent. So, what if a class needs to inherit multiple behaviors? OOP traits solve this problem. Traits are used to declare methods that can be used in multiple classes. Traits can have methods and abstract methods that can be used in multiple classes, and the methods can have any access modifier (public, private, or protected). Traits are declared with the trait keyword:

Why PHP?

PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.) PHP is compatible with almost all servers used today (Apache, IIS, 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

access modifier

Properties and methods can have access modifiers which control where they can be accessed. There are three access modifiers: public - the property or method can be accessed from everywhere. This is default protected - the property or method can be accessed within the class and by classes derived from that class private - the property or method can ONLY be accessed within the class In the following example we have added three different access modifiers to three properties (name, color, and weight). Here, if you try to set the name property it will work fine (because the name property is public, and can be accessed from everywhere). However, if you try to set the color or weight property it will result in a fatal error (because the color and weight property are protected and private):

try-catch-finally block

Provides a way to handle some or all possible errors that may occur in a given block of code, while still running code in the finally section regardlers if an error occurs

PHP Global Variables - Superglobals

Some 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. The PHP superglobal variables are: $GLOBALS $_SERVER $_REQUEST $_POST $_GET $_FILES $_ENV $_COOKIE $_SESSION

PHP Casting Strings and Floats to Integers

Sometimes you need to cast a numerical value into another data type. The (int), (integer), and intval() functions are often used to convert a value to an integer. Example

static methods

Static methods can be called directly - without creating an instance of the class first. Static methods are declared with the static keyword:

PHP data types

String Integer Float (floating point numbers - also called double) Boolean Array Object NULL Resource

The $this Keyword

The $this keyword refers to the current object, and is only available inside methods.

PHP Continue

The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop. This example skips the value of 4:

global keyword

The global keyword is used to access a global variable from within a function. To do this, use the global keyword before the variables (inside the function):

simple form , but with $_GET

The same result could also be achieved using the HTTP GET method:

how to see what type a variable is in PHP

To get the data type of a variable, use the var_dump() function

Return keyword

To let a function return a value, use the return statement:

Parent Keyword

To refer to a member of a parent class, use the scope resolution operator with the keyword parent: class SomeOtherClass extends SomeClass{ function _ _construct() { parent::doThis(); } }

What do I need to start using PHP

To start using PHP, you can: Find a web host with PHP and MySQL support Install a web server on your own PC, and then install PHP and MySQL

in a php codebase, when should I use JavaScript logic vs PHP logic?

Use PHP for server-side tasks: This includes interacting with databases, processing form submissions, handling server-side logic, managing user sessions and authentication, and rendering initial HTML content. Use JavaScript for client-side functionality: This covers dynamic content updates without page reloads (using AJAX), user interface interactivity (like dropdowns, modals, tooltips), real-time features (such as chat functionalities), client-side form validations, and DOM manipulations.

in a php codebase, when should I use JavaScript logic vs PHP logic?

Use PHP for: Server-Side Logic: Operations that require server resources, like accessing a database, processing form data, handling file uploads, or executing server-side calculations. Generating dynamic HTML content based on server-side data before sending it to the client. Initial Page Rendering: Rendering the initial state of web pages. PHP can dynamically generate HTML content based on current data, user sessions, or other server-side conditions. Authentication and Security: Handling user authentication, authorization, and sensitive operations like password hashing and session management. Data Processing: Complex data manipulations that are resource-intensive or require access to server-side resources, like data aggregation, filtering, or conversion. API Interaction: Interacting with server-side APIs or web services, especially when it involves sensitive data or credentials that should not be exposed on the client side. Use JavaScript for: Client-Side Interactivity: Enhancing user interaction and experience, like responding to user actions, validating user input in forms before submission, or creating interactive elements like sliders, modals, and dropdown menus. Asynchronous Data Fetching (AJAX): Making asynchronous requests to the server (using AJAX) for loading or submitting data without reloading the entire page. This is key for dynamic content updates. Real-Time Updates: Implementing real-time features, like live chat, notifications, or real-time data updates Client-Side Validation: Providing immediate feedback to users on form inputs before sending data to the server, thereby reducing server load and improving user experience. Manipulating the DOM: Dynamically changing the Document Object Model (DOM) of a web page in response to user actions, without needing to reload the page.

Throwing an Exception

What is an Exception? An exception is an object that describes an error or unexpected behaviour of a PHP script. Exceptions are thrown by many PHP functions and classes. User defined functions and classes can also throw exceptions. Exceptions are a good way to stop a function when it comes across data that it cannot use. The throw statement allows a user defined function or method to throw an exception. When an exception is thrown, the code following it will not be executed. If an exception is not caught, a fatal error will occur with an "Uncaught Exception" message. Lets try to throw an exception without catching it:

simple PHP form

When the user fills out the form above and clicks the submit button, the form data is sent for processing to a PHP file named "welcome.php". The form data is sent with the HTTP POST method. To display the submitted data you could simply echo all the variables

how to use apache to host and(or)serve your site

When you place your PHP site files in the www (or equivalent) directory within your WampServer installation folder, you're essentially making your site accessible through the Apache web server that comes with WampServer. everytime you want to create a new site, create a folder in the wamp's www folder

what is echo?

With PHP, there are two basic ways to get output: echo and print. In this tutorial we use echo or print in almost every example. So, this chapter contains a little more info about those two output statements. The echo statement can be used with or without parentheses: echo or echo(). Display Text The following example shows how to output text with the echo command (notice that the text can contain HTML markup)

PHP const Keyword

You can also create a constant by using the const keyword.

PHP - instanceof

You can use the instanceof keyword to check if an object belongs to a specific class

take a look at all the built in PHP functions

at w3schools

note*

built methods such as array methods and string manipulation built methods are named differently than javascript but both share methods of the same functionalities , just named differently and/or slightly differertn

const vs define()

const are always case-sensitive define() has has a case-insensitive option. const cannot be created inside another block scope, like inside a function or inside an if statement. define can be created inside another block scope.

PHP Functions

define like a javascript functions. Take a look at all the built in function on W3schools

Do While loop

do { code to be executed;} while (condition is true);

for loop

for (init counter; test counter; increment counter) { code to be executed for each iteration;}

foreach loop

foreach ($array as $value) { code to be executed;}

arrays in php

in older codebases you may see arrays defined with () instead of [] old way: $numericArray = array(1, 2, 3, 4, 5); new way: $numericArray= [1,2,3,4,5];

To start using PHP you need?

install a web server install PHP install a database, such as MySQL

PHP variables are NOT strongly typed

notice that we did not have to tell PHP which data type the variable is. PHP automatically associates a data type to the variable, depending on its value. Since the data types are not set in a strict sense, you can do things like adding a string to an integer without causing an error. In PHP 7, type declarations were added. This gives an option to specify the data type expected when declaring a function, and by enabling the strict requirement, it will throw a "Fatal Error" on a type mismatch.

PHP Arrays

old way of declaring an array is: $cars = array("Volvo","BMW","Toyota"); the new way of declaring is :" $cars = ["Volvo","BMW","Toyota"]; In PHP, there are three types of arrays: Indexed arrays - Arrays with a numeric index Associative arrays - Arrays with named keys Multidimensional arrays - Arrays containing one or more arrays

PHP VS code color schemes

pale yellow= built in functions light blue= custome variables red= string datatype?

include

put the navbar(header) in the incudes folder.now the navabr/header is includes in this page just by using 1 line, good for navbars, since if you want to tmake a change, you only have to chnage the header filre and the rest of the pages headeer changes with it( kinda like js's import)

composer init

run this cli command if youy want to create an PHP app creates a composer.json file, src folder, and vendor folder, populate composer.json with the libraries you need , then run composer install

if/else statements in PHP

same as other languages

switch statements in php

same as other languages

require

same thing as include , but if the file cannot be found then page does not work, with include , if the file cannot be found, the page still works just without the file that was suppsoed to be includedded. ( kinda like js's import). there is also require_once whicht is similar to require but with an important distinction: it checks if the file has already been included during the script's execution, and if so, it will not include and evaluate it again. This is particularly useful for situations where the same file might be included multiple times accidentally, which could lead to redeclaration errors, particularly with functions or classes.

concatenating strings vs concatenation varaibles syntax

see pic

string functions

see www.w3schools/php/php_ref_string.asp

string escape characters

see www.w3schools/php/php_string_escape.asp

note*

try to use double quotes for all strings

PHP Break

u have already seen the break statement used in an earlier chapter of this tutorial. It was used to "jump out" of a switch statement. The break statement can also be used to jump out of a loop. This example jumps out of the loop when x is equal to 4:

while loop

while (condition is true) { code to be executed;}

re-assigning variables

yes you can re-assign values to variables


Kaugnay na mga set ng pag-aaral

Ch 19: Growth, Development, & Stages of Life

View Set

Chapter 17: Limited Liability Business Forms

View Set

Chapter 11: Cooperative and Agricultural Credit

View Set

Operating Systems Fundamentals (CINS-120) UNIT 1 Exam 1-3 Practice

View Set

4.7 (Solar Radiation and Seasons

View Set

Human Relations Chapter Chapter 2 Study Guide

View Set

Chapter 1-4 review C++ Programming

View Set