22.03.21 - PHP
Origins
- 1994, open source project
- Used to be an acronym for Personal Home Page
- Used for from handling, file processing and database access
- Is a server-side scripting language whose scripts are embedded in HTML documents.
- OOP language. PHP is interpreted and is dynamically typed
Basic Features
PHP code can be specified in an HTML document using
<?php ?>
To declare and use variables use $
symbol. Dont have to specify what data type it is.
Use echo
to output to display, similar to how print works
Control statements are the same as C and Javascript
Strings
converts $msgs into a string like + in java script
String functions
- chop - remove white space from the right end
- trim - remove white space from both ends
- ltrim - remove white space from the left end
Arrays
- A PHP array is a generalisation of the arrays of other languages
- A PHP array is a mapping of keys to values, where the keys can be numbers or strings
- Use array() construct, which takes one or more key => value pairs as parameters and returns an array of them (basically a dictionary)
- Loops are the same as in C and Javascript
- Can use foreach - goes through each item in an array and does something
Array Methods
is_array()
- check if a variable is an arrayunset()
- to destroy an arraycount()
- to sort an arrayshuffle()
- to shuffle the elements of an arrayexplode()
- to convert the words of a sentence into an array
Functions
Objects are passed by reference Everything else by value
Other
- Can include library by using include
- Can also define a class destructor - Called when you remove an object
- Can also easily clone objects by using clone
Inheritance
- Data members can be declared public, private and protected
- Can override a function implemented in the base class with a function in the derived class
To access database, use MySQLi extension. Has multiple benefits:
- Object-oriented interface
- Support for prepared statements
- Support for multiple statements
- Support for transactions
SQL
MySQL database supports prepared statements. Used to execute the same statement repeatedly with high efficiency. Consists of 2 stages, prepare and execute.
- Prepare stage: Statement template is sent to the database server so it can perform syntax check and initialise the server
- Execute stage:Client binds parameter values and sends them to the server. Server then creates a statement