Basic knowledge of php

Keywords: PHP PDO Database MySQL

Basic introduction

php marker <? php?>

If the content of the file is pure PHP code, delete the PHP end tag at the end of the file. You can avoid accidentally adding spaces or newlines after the end tag of PHP, which will cause PHP to start outputting these blanks without the intention of output in the script at this time.

<?php
echo "Hello world";
echo "Last statement";
// The script ends here, and there is no PHP end tag
  • php runs as pure scripting code

  • php executes as CGI

php embedded in html for execution

index.html file

<html>
<head>
  <meta charset="utf-8">
</head>
<body>
<?php if ($expression == true): ?>
  This will show if the expression is true.
<?php else: ?>
  Otherwise this will show.
<?php endif; ?>
</body>
</html>

index.php file

<?php
$expression = true;
include(relpath('./').'/index.html');

data type

PHP supports eight original data types.

  1. Four scalar types:
    • boolean
    • integer (integer)
    • float (floating-point type, also known as double)
    • String (string)
  2. Two types of composite:
    • array
    • object
  3. Two Special Types
    • resource (Resources)
    • null (untyped)
<?php

// String connection
$num = 12.8;
$string = "this is world".$num;

// Using variables in double quotation marks
$world = "world";
$hello = "hello {$world}";

// Escaping Special Characters
$class_name = "\\name";
echo $class_name;

// array
$array = array(
    "foo" => "bar",
    "bar" => "foo",
    100   => -100,
    -100  => 100,
);
var_dump($array['foo']);
unset ($array[100]);
$array["x"] = 42;


// An index array without a key name
$array = array("foo", "bar", "hallo", "world");
var_dump($array);

// ergodic
foreach ($array as $key => $value) {
  var_dump($key, $value);
}

// object
class foo
{
    function do_foo()
    {
        echo "Doing foo.";
    }
}

$bar = new foo;
$bar->do_foo();

?>
  • gettype() function gives the type of variable
  • is_[type]() function can be used to determine whether a variable is of a certain type or not.
  • The var_dump() function outputs the type and value of the variable

false in php

When necessary, the boolean() function can be called to implement the transformation. When converted to boolean, the following values are considered FALSE:

  • Boolean FALSE itself
  • Integer value 0 (zero)
  • Floating point value 0.0 (zero)
  • Empty string, and string "0"
  • Arrays that do not include any elements
  • Objects that do not include any member variables (only PHP 4.0 applies)
  • Special types of NULL (including variables that have not yet been assigned)
  • SimpleXML objects generated from empty Tags
  • Except for the above, all are true.

There is no divisive operator in PHP. 1/2 produces float 0.5. Values can be forcibly converted to integer by discarding decimal parts, or rounding can be better done by using round() functions

To use octal representation, the number must be preceded by 0 (zero). To use hexadecimal representation, the number must be preceded by 0x. To use binary representation, the number must be preceded by 0b

A string consists of a series of characters, each of which is equal to a byte. This means that PHP only supports 256 character sets, so Unicode is not supported.

Resource resource resource is a special variable, which saves a reference to an external resource. It can be determined by the is_resource() function whether a variable is a resource or not, and the function get_resource_type() returns the type of the resource.

NULL values indicate that a variable has no value. The only possible value for a NULL type is NULL. A variable is considered NULL: 1. assigned to NULL 2. not yet assigned to 3. unset().

Some functions such as call_user_func() or usort() can accept user-defined callback functions as parameters. Callback functions can be not only simple functions, but also methods of objects, including static class methods.

variable

Predefined variables

Scope of php variable

External variables cannot be accessed inside functions in php, and $GLOBALS can be output for details.

Global variables in php must be declared global when used in functions

<?php
$a = 1;
$b = 2;

function Sum()
{
    global $a, $b;
    $b = $a + $b;
}

Sum();
echo $b;

Using static variables

<?php
function fac($number)
{
  static $sum = 0;
  echo $sum . "\n";

  if ($number == 0) {
    $sum += $number;
    return 1;
  } else {
    $sum += $number;
    return $number * fac($number - 1);
  }
}
echo fac(4);

constant

<?php

// Legal Constant Name
define("FOO",     "something");
define("FOO2",    "something else");
define("FOO_BAR", "something more");

// Illegal constant names
define("2FOO",    "something");

// The following definition is legal, but it should be avoided: (custom constants should not begin with)
// Maybe someday PHP will define a magic constant of _FOO_____________
// This will conflict with your code.
define("__FOO__", "something");

PHP provides a large number of predefined constants to any script it runs. However, many constants are defined by different extension libraries, which only occur when they are loaded, either dynamically loaded, or included at compile time.

Predefined Constants

<?php
class System {
  const OS_UNKNOWN = 1;
  const OS_WIN = 2;
  const OS_LINUX = 3;
  const OS_OSX = 4;

  /**
   * @return int
   */
  static public function getOS() {
    switch (true) {
      case stristr(PHP_OS, 'DAR'): return self::OS_OSX;
      case stristr(PHP_OS, 'WIN'): return self::OS_WIN;
      case stristr(PHP_OS, 'LINUX'): return self::OS_LINUX;
      default : return self::OS_UNKNOWN;
    }
  }
}

Common Magic Constants

__DIR__ __FILE__ __METHOD__ __NAMESPACE__

Expression

Anything of value

operator

Normal operators commonly include three-element expressions

Process control

  • if
  • else
  • elseif
  • Alternative Grammar for Process Control

    PHP provides some alternative syntax for process control, including if, while, for, foreach, and switch. The basic form of alternative grammar is to replace left brackets ({) with colons (:), right brackets (}) with endif;, endwhile;, endfor;, endforeach; and endswitch; usually used in html pages.

    <body>
      <?php if ($a == 5): ?>
      A is equal to 5
      <?php endif; ?>
    </body>
    
  • while
  • do-while
  • for
  • foreach

    Use references in traversal

    <?php
    $arr = array(1, 2, 3, 4);
    foreach ($arr as &$value) {
      $value = $value * 2;
    }
    // $arr becomes (2, 4, 6, 8)
    unset($value); // Finally, remove the reference
    ?>
    
  • break
  • continue
  • switch
  • return
  • require

    require and include are almost identical, except that failure is handled differently. Requirement generates an error at the E_COMPILE_ERROR level when an error occurs. In other words, it will cause the script to abort and include will only produce warnings (E_WARNING), and the script will continue to run.

  • include
  • require_once

    The require_once statement is identical to the require statement, except that PHP checks whether the file has been included and if so, does not include it again.

  • include_once

function

Normal function usage

<?php
function foo($arg_1, $arg_2, /* ..., */ $arg_n)
{
    echo "Example function.\n";
    return $retval;
}

By default, function parameters are passed by value (so even if the value of the parameter is changed inside the function, it does not change the value outside the function). If you want to allow a function to modify its parameter values, you must pass parameters by reference

<?php
function add_some_extra(&$string)
{
    $string .= 'and something extra.';
}
$str = 'This is a string, ';
add_some_extra($str);
echo $str;
?>

Use default parameters in functions

<?php
function makecoffee($type = "cappuccino")
{
    return "Making a cup of $type.\n";
}
echo makecoffee();
echo makecoffee(null);
echo makecoffee("espresso");
?>

Types of Limited Function Parameters

<?php
class C {}
class D extends C {}

// No inheritance of C
class E {}

function f(C $c) {
    echo get_class($c)."\n";
}

f(new C);
f(new D);
f(new E); // Errors will be reported here.
?>

Variable function

PHP supports the concept of variable functions. This means that if a variable name is followed by parentheses, PHP will look for functions with the same name as the value of the variable and try to execute it. Variable functions can be used for some purposes, including callback functions and function tables.

Variable functions cannot be used for example echo(), print(), unset(), isset(), empty(), include(), require(), and similar language structures. You need to use your own wrapper functions to use these structures as variable functions.

<?php
$method = "action";
function action()
{
  echo "foo";
}
// Variable function
$method();

Internal (built-in) functions

PHP has many standard functions and structures. There are also functions that need to be compiled with specific PHP extension modules, otherwise you will get a fatal "undefined function" error when using them. For example, to use imagecreatetruecolor() in the image function, you need to add GD support when compiling PHP. Or, to use the mysql_connect() function, you need to add MySQL support when compiling PHP. There are many core functions already included in each version of PHP, such as strings and variable functions. Call phpinfo() or get_loaded_extensions() You can see that PHP loads those extension libraries. It should also be noted that many extension libraries are valid by default.

Common functions

isset() empty() unset() explode() sub_str() mb_sub_str() in_array() array_unique()str_replace()

Class and object

<?php
class simpleClass
{
  // The public representative can be accessed anywhere.
  public $var = 'a default value';

  // Class Constants
  const pi = 3.1415926;

  // A method accessible anywhere
  public function displayVar()
  {
    //this is a reference to the main object
    echo $this->var;
  }
}
// Generate an object with new keywords
var simple = new simpleClass();

// Inheritance of the previous class
class extendClass extends simplerClass
{
  function displayVar()
  {
    echo "Extending class\n";
    //Calling methods in parent classes
    parent::displayVar();
  }
}

Automatic loading class

<?php
class core
{
  public static function load()
  {
    // include
  }
}
spl_autoload_register('core::load');

// Calling a method specified in the nonexistent class spl_autoload_register will be called
// Class name core lib route or pass in core::load method as a parameter
new \core\lib\route();

Constructor

<?php
class core
{
  public $action =  'index';
  function __construct($action)
  {
    public $action = $action;
  }
}

<?php
class route extends core
{
  function __construct()
  {
    // Call the constructor of the parent class
    parent::__construct();
  }
}

Scope Resolution Operational Symbols

Range resolution operators (also known as Paamayim Nekudotayim) or, more simply, a pair of colons can be used to access static members, class constants, and to override properties and methods in classes.

<?php

// Use outside the class
class MyClass {
  const CONST_VALUE = 'A constant value';
}

$classname = 'MyClass';
// Since PHP 5.3.0
echo $classname::CONST_VALUE;

echo MyClass::CONST_VALUE;

// Use within a class
class OtherClass extends MyClass
{
  // static keyword is the key to using range resolver
  public static $my_static = 'static var';

  public static function doubleColon() {
    echo parent::CONST_VALUE . "\n";
    echo self::$my_static . "\n";
  }
}

$classname = 'OtherClass';
echo $classname::doubleColon(); // Since PHP 5.3.0
OtherClass::doubleColon();

PHP treats objects in the same way as references and handles, that is, each variable holds a reference to an object rather than a copy of the entire object.

Attribute declarations are made up of keywords public, protected or private, followed by a common variable declaration. Variables in attributes can be initialized, but the initialized value must be constant, which means that the PHP script can get its value at the compilation stage without depending on the runtime information. Default public

Access control to attributes or methods is achieved by adding keywords public (public), protected (protected) or private (private) to the front. Class members defined as public can be accessed anywhere. Class members defined as protected can be accessed by themselves and their children and parents. A class member defined as private can only be accessed by the class in which it is defined.

Declaring class attributes or methods as static allows direct access without instantiating classes. Static attributes cannot be accessed through a class of instantiated objects (but static methods can). Because static methods are unique in a namespace

Traversing objects using foreach as well

Namespace

In PHP, namespaces are used to solve two types of problems encountered in creating reusable code such as classes or functions when writing class libraries or applications:

  • User-written code conflicts with the names of classes/functions/constants within PHP or third-party classes/functions/constants.
  • Create an alias (or short) name for a long identifier name (usually defined to alleviate the first type of problem) to improve the readability of the source code.
  • Generally, folder names are used as namespaces

/index.php

<?php
include(realpath('./').'/lib/core.php');
// Static method
\lib\core::load();

// Non-static method
$o = new \lib\core();
$o->dump();

/lib/core.php

<?php
namespace lib;
class core
{
  public function dump()
  {
    //code
  }
  public static function load()
  {
    //code
  }
}

Connecting database with PDO

The MySQL API and the upgraded version of mysqli are built into php to manipulate mysql, but they are flawed whether they use the native MySQL API or MySQLi.

  1. Transaction mechanism is not supported;
  2. MySQL is only supported and no other databases can be used.
  3. Insecurity, possibly injection risk
  4. Exception handling is not supported

The PDO extensions that PHP subsequently introduced solved these problems skillfully.

  • PDO uses dsn connection to support many types of databases, such as mysql,postgresql,oracle,mssql and so on.
  • PDO(php data object) extended class library defines a lightweight and consistent interface for PHP to access database, which provides a database access abstraction layer. In this way, no matter what database you use, you can query and retrieve data through consistent functions.
  • PDO greatly simplifies the operation of database and can shield the difference between different databases. Using PDO can easily develop cross-database programs and transplant different databases. It is the main development direction of php in database processing in the future.
<?php

$db = array(
  'dsn' => 'mysql:host=localhost;dbname=test;port=3306;charset=utf8',
  'host' => 'localhost',
  'port' => '3306',
  'dbname' => 'yarn',
  'username' => 'root',
  'password' => 'root',
  'charset' => 'utf8',
);

//Connect
$options = array(
  //The default is PDO::ERRMODE_SILENT, 0, (ignoring error mode)
  PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
  // The default is PDO::FETCH_BOTH, 4
  PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
);

try{
  $pdo = new PDO($db['dsn'], $db['username'], $db['password'], $options);
}catch(PDOException $e){
  die('Failure of database connection:' . $e->getMessage());
}

//Or a more general way to set properties:
//Setting exception handling mode
//$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Setting default associated index traversal
//$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

echo '<pre/>';

//1 query

//1) Use query
//Returns a PDOStatement object
$stmt = $pdo->query('select * from user limit 2');

//Get the next row from the result set for the while loop
//$row = $stmt->fetch();
//Get all
$rows = $stmt->fetchAll();

$row_count = $stmt->rowCount();
//print_r($rows);

echo '<br>';

//2) Use prepare Recommendation
$stmt = $pdo->prepare("select * from user where name = ? and age = ? ");
$stmt->bindValue(1,'test');
$stmt->bindValue(2,22);
//Execute a preprocessing statement. Return TRUE on success and FALSE on failure
$stmt->execute();  
$rows = $stmt->fetchAll();
print_r($rows);



//2 Added, updated, deleted
//1) General operation
//$count  =  $pdo->exec("insert into user(name,gender,age)values('test',2,23)");
//echo $pdo->lastInsertId();

//$count  =  $pdo->exec("update user set name='test2' where id = 15");
//$count  =  $pdo->exec("delete from  user where id = 15");


//2) Use prepare Recommendation!
/*
$stmt = $pdo->prepare("insert into user(name,gender,age)values(?,?,?)");
$stmt->bindValue(1, 'test');
$stmt->bindValue(2, 2);
$stmt->bindValue(3, 23);
$stmt->execute();
*/

//3) New batches using prepare s
$stmt = $pdo->prepare("insert into user(name,gender,age)values(?,?,?)");
$stmt->bindParam(1, $name);
$stmt->bindParam(2, $gender);
$stmt->bindParam(3, $age);

$data = array(
  array('t1', 1, 22),
  array('t2', 2, 23),
);

foreach ($data as $vo){
  list($name, $gender, $age) = $vo;
  $stmt->execute();
}

pdo transaction

<?php
//Open transaction processing
$pdo->beginTransaction();

try{
  //PDO preprocessing and execution statement.
  $pdo->commit();
}catch(PDOException $e){
  $pdo->rollBack();

  //Correlated error handling
  throw $e;
}
header("Location: http://example.com/myOtherPage.php");

Posted by makeshift on Mon, 01 Apr 2019 12:24:29 -0700