PHP most important concepts, syntax list?

PHP most important concepts, syntax list?

This article can be useful for those that want to get back on track with php, remember most of the basic syntax for this programming language.
It can be very useful if you are going tomorrow or the next days on a job interview, just to get back with the syntax.

PHP stands for “Hypertext Processor”.

The php code is executed on the server and is shipped to the user in the browser. The user never sees the php code from the backend.

You can even write php desktop programs with php GTK, website is here: http://gtk.php.net/

$_SERVER[‘HTTP_USER_AGENT’];

$_SERVER[‘HTTP_USER_AGENT’]; is a superglobal. A list with all the superglobal in php: http://php.net/manual/en/language.variables.superglobals.php.

strpos() is a function built into PHP which searches a string for another string.

Use if / else outside php to strip weird code

You can use if / else outside php and not use echo to return the results.
Here is an example:

1
2
3
4
5
6
7
8
9
10
11
12
13
<?php
$var = 1;
$var2 = 2;
if ($var == $var2){
	?>
    <p>False</p>
    <?php
}
else{
	?>
    <p>True</p>
    <?php
}?>

You might have noticed this in the wordpress syntax. WordPress makes good use of these methods to return html data with if else.

You can just not close your page with the php tags “?>” if the page is a pure php page with no html code.

PHP types

boolean = true or false.
integers = numbers.
floats.
string = a series of characters. A sentence is usually a string. Best way to use a string is with single quotes.

About arrays

arrays = ordered map
Array example:

2
3
4
5
$array = [
    "foo" => "bar",
    "bar" => "foo",
];

Arrays without key:

3
4
5
$array = array("Neo", "action" => "fights", "Morpheus");
 
echo $array['action'];

you can access this with $array[‘action’]; It will echo “fights”.

“action” is the key here. You won’t be able to do $array[1]; to echo “fights”.

unset($array) will delete the whole array.

& in front of a $variable

& in front of $variable is a reference to another variable from above.
Example:

$a = 3;
$b = &$a;

$b = 4;
echo $a;

will echo “4” because $b = $a because of the “&” sign.

Objects

Objects in php are classes. Classes are objects.

Example:

4
5
6
7
8
9
10
11
12
13
14
15
<?php
class foo
{
    function do_foo()
    {
        echo "Doing foo."; 
    }
}
 
$bar = new foo;
$bar->do_foo();
?>

var_dump() checks the type and value of an expression.
Example:

5
6
7
8
9
<?php
$var = 2;
 
var_dump($var);
?>

Will return that your variable has an integer value.

You can also use gettype(); like this:

6
7
8
9
10
<?php
$var = 2;
 
echo gettype($var);
?>

It will echo “integer”.

You can check if a variable exists with isset(); isset(); doesn’t check if the variable has a value, it checks if it exists.

To get a variable from outside a function into a function, you can use “global”.

Example:

7
8
9
10
11
12
13
14
15
16
<?php
$var = 'cristi';
function eat(){
	global $var;
	echo ''.$var.' eats fruits';	
}
 
 
echo eat();
?>

Double variable: $$var; example:

8
9
10
11
12
<?php
$var = 'cristi';
$var2 = 'var';
echo $$var2;
?>

So $var2; contains “var” which is the name of the first variable.
If you call $$var2; it will echo the content of $var;
Can’t say it is very useful, but it’s good to know about it.

Constants

here is an easy example:

9
10
11
12
<?php
define("NAME", "cristi");
echo NAME;
?>

Constants are case sensitive.

Pretty much everything in php is an expression:
$a = 5; is an actual expression in php.

Adding value to a variable.
You can use this code:

10
11
12
13
14
<?php
$a = 2;
$a += 4;
echo $a;
?>

This will basically add 4 to the current $a variable.
Now you know what this syntax means.

Another example:

11
12
13
14
15
16
17
<?php
 
$a = 2;
$a *= 4;
echo $a;
 
?>

Will echo “8”.

1 + 5 * 3 = 18 because * has higher importance than +. If you want to get 16, use (1+5)*3; and you will get 16.

&& / || have higher priority than “and” / “or”.

= in php means “assign”, not equal.

$a += $b is the same as $a + $b;

$a .= $b is the same as $a . $b; (it’s called concatenate).

In php, these comparison operators mean:

= assign
== equal
=== identical
!=== not identical
!= not equal
<> not equal
<= less or equal than >= greater or equal than (remember the > is always the first element).

Ternary operator

Example:

12
13
14
15
16
17
<?php
$a = 22;
$b = 443;
$answer = ($a > 2) ? 3 : 2;
echo $answer;
?>

It will echo 3. You can’t put echo inside the ternary operator.

Here is an example for echo.

13
14
15
16
17
<?php
$a = 22;
$b = 443;
echo ($a > 2) ? 3 : 2;
?>

It will echo ‘3’;

The ternary syntax is this:

first compare something, ? = if : = else.

You can find more about the ternary operator here: http://php.net/manual/en/language.operators.comparison.php.

I’ve noticed that many php programmers are often using ternary operators in their code, so it’s good to know the syntax.

@ (operator) in front of some custom php functions will supress displaying errors, like @unlink. Will not display an error if the file that you want to delete does not exist.

++$var means pre-increment.
Example:

14
15
16
17
<?php
$a = 22;
echo ++$a;
?>

Will echo 23.

15
16
17
18
<?php
$a = 22;
echo $a++;
?>

Will echo 22.

16
17
18
19
20
<?php
$a = 22;
$a++;
echo $a;
?>

Will echo 23.

The difference here is that ++$var will increase and display the new $var while $var++; will only increase the $var but it will not display the new $var at the same time.

For operator

Example:

17
18
19
20
21
<?php
for ($a = 2; $a < 10; $a++){
	echo $a;	
}
?>

For and while can do the same thing.

Example:

18
19
20
21
22
<?php
for ($a = 2; $a < 10; $a++){
	echo $a;	
}
?>
19
20
21
22
23
24
25
<?php
$a = 2;
while ($a < 10){
	echo $a;
	$a++;	
}
?>

A few examples for how to use if else to have javascript or other weird code outside an echo.

20
21
22
23
24
<?php if (2 < 3) : ?>
test
<?php else : ?>
false
<?php endif ?>
21
22
23
24
25
<?php
if (2 < 3) {
?>
test
<?php } ?>

Another syntax for if in php is this one:

22
23
24
25
26
<?php
if (2 < 3):
echo 'true';
endif;
?>

Here is a nice script to generate the alphabet with a for loop:

23
24
25
26
27
<?php
for ($var = "A"; $var != "AA"; $var++){
	echo $var. ' ';	
}
?>

This will only work with the != operator, not with something like <=. Foreach works with arrays and objects. You might want to use it mostly on arrays. More about foreach here: http://php.net/manual/en/control-structures.foreach.php

Break (break;) will stop a script.

Example:

24
25
26
27
28
<?php
echo 'hello';
break;
echo 'hello to you too';
?>

Will only echo “hello”. The code is stopped after break;

Switch

This is the switch syntax, quite different than the usual php syntax.

25
26
27
28
29
30
31
32
33
34
35
36
37
<?php
$var = 'apple';
 
switch($var){
	case 'kiwi':
	echo 'kiwi';
	break;
 
	case 'apple':
	echo 'apple';
	break;
}
?>

It might look like a function, starts with switch($var){}

And has cases like: case ‘kiwi’: (notice that it ends with colon instead of paranthesis. It also has break.

Another example, a switch can use strings, integers etc.

26
27
28
29
30
31
32
33
34
35
36
37
38
<?php
 
$var = 2;
switch ($var){
	case 1:
	echo '1';
	break;
 
	case 2:
	echo '2';
	break;	
}
?>

First write the switch as a function:

switch($var{

}

Then add the case:

case 1:
echo ‘something’;
break;

and add more cases.

The concept is pretty easy but as the syntax is different than the other php syntax, you might forget about it. But you can check it out here.

If your case is empty, use this code:

27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<?php
 
$var = 5;
switch ($var){
	case 1:
	echo '1';
	break;
 
	case 2:
	echo '2';
	break;
 
	case 3:
	case 4:
	case 5:
	echo '5';
	break;
}
?>

You might also want to add a default case to your switch.

Like this:

default:
echo ‘missing number’;

Full example:

28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
 
<?php
 
$var = 6;
 
switch ($var){
	case 1:
	echo '1';
	break;
 
	case 2:
	echo '2';
	break;
 
	case 3:
	case 4:
	case 5:
	echo '5';
	break;
 
	default:
	echo 'missing number';
}
?>

Default acts like “else”. If nothing is true, return the value inside default.
No need to add break; after default:

Return. Return will break a function. If you put return in a function and you write code below it, like another echo, the second echo will not be displayed when you run that function.

Example:

29
30
31
32
33
34
35
36
37
38
39
<?php
 
function eat (){
	$person = 'he eats food';
	return $person;
 
	echo 'test';
}
 
echo eat();
?>

Will only echo ‘he eats food’;

if you put echo instead of return, you will get the full echos, ‘he eats foodtext’;

To get a variable from a function, use this code:

30
31
32
33
34
35
36
37
38
39
40
<?php
 
function eat (){
	$person = 'he eats food';
 
	echo $person;
}
 
$var =  eat();
echo $var;
?>

Require is similar to include, but it will produce an error if the file you require is missing.

If you want to use require or include in a function, do it like this:

31
32
33
34
35
36
37
38
39
40
<?php
 
function eat(){
	require('include.php');
	echo $fruit;	
}
 
eat();
 
?>

You also get the same results with this, by adding the parameters inside the function, but you write more code and more paramenters. In a function is harder to follow:

32
33
34
35
36
37
38
39
40
41
<?php
require('include.php');
 
function eat($fruit, $connection){
	echo $fruit;	
}
 
eat($fruit, $connection);
// assuming that $connection is the connect variable from include.php
?>

Functions are independend of the other code from your php page.

Function within function

Here is an example:

33
34
35
36
37
38
39
40
41
42
43
<?php
 
function eat(){
	function dream(){
		echo 'test';	
	}
}
eat();
dream();
 
?>

To echo test; you need to call both functions. If you call just dream();, it won’t work. If you call just eat();, it won’t work either.

&$var inside a function as argument?

It is called reference argument.

Here is an example:

34
35
36
37
38
39
40
41
42
<?php
function eats(&$who){
	$who .= ' eats';	
}
$who = 'Cristi';
eats($who);
echo $who;
 
?>

As you see in the example, it is used for concatenation, with $who .= to obtain a longer string, “Cristi eats”.

Function with default parameters.

If no parameter/parameters are provided, you can assign a default parameter inside the function like this:

35
36
37
38
39
40
41
42
43
44
<?php
function eat($type = "cappuccino")
{
    return 'Making a cup of '.$type;
}
 
$eat = eat();
echo $eat;
 
?>

It will echo “cappuccino”.

If you put an argument inside eat(); like expresso”, it will echo with “expresso”.

Another interesting example:

36
37
38
39
40
41
42
43
44
45
<?php
function eat($test, $type = "cappuccino")
{
    return 'Making a cup of '.$type . ' ' .$test;
}
 
$eat = eat("hello");
echo $eat;
 
?>

Remember that you should pass the default argument after the initial arguments that are non-default.

Objects

Objects start with class{ (similar to functions).

class test{

}

This is an object.

Classes can contain methods (normal functions). These normal functions are called methods when being inside an object.
An object can also contain variables or constants.

A basic object in php:

37
38
39
40
41
42
43
44
45
46
47
48
<?php
 
class eat{
	public function action(){
		echo 'He eats';	
	}
}
 
$obj = new eat();
 
echo $obj->action();
?>

Object with argument inside the method:

38
39
40
41
42
43
44
45
46
47
48
49
<?php
 
class eat{
	public function action($who){
		echo $who. ' eats';	
	}
}
 
$obj = new eat();
 
echo $obj->action("Cristi");
?>

Another example:

39
40
41
42
43
44
45
46
47
48
49
50
51
52
<?php
 
class eat{
	public $name = 'cristi';
 
	public function action(){
		echo $this->name. ' eats';	
	}
}
 
$obj = new eat();
 
echo $obj->action();
?>

To create a new instance of a class (object), use the keyworkd “new”.

Like: new eat();

You can use a variable like:

$var = new eat();

If you want to echo a variable from an object, use:

40
41
42
43
44
45
46
47
48
49
50
51
52
53
<?php
 
class eat{
	public $name = 'cristi';
 
	public function action(){
		echo $this->name. ' eats';	
	}
}
 
$obj = new eat();
 
echo $obj->name;
?>

That variable is called a “property”.

Basic object extend:

41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<?php
 
class var1{
 
	function test(){
		echo 'hello';	
	}
 
	function greet(){
		echo 'hey bro';	
	}
 
 
}
 
class var2 extends var1{
	function test(){
		echo 'help';	
	}
}
 
$var = new var2;
echo $var->test();
 
?>

You can easily convert functions into objects. It is somehow good to have functions and object because you can just copy/paste them from a project to another project.

Variables inside objects are called properties.
They can be private, public or protected properties (variables).

-> is called object operator.

$this->property

$this can be used inside any objects and object methods (functions) and it is used mostly in constructs.

Here is an example:

42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?php
 
class test{
	public $name;
	public function __construct($name){
		$this->name = $name;
	}
 
	function eat(){
		echo $this->name. ' eats';	
	}
}
 
$var = new test("Cristi");
echo $var->eat();
 
?>

If you would use this instead:

43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<?php
 
class test{
	public $name;
	public function __construct($name){
		$this->name = $name;
	}
 
	function eat(){
		echo $name. ' eats';	
	}
}
 
$var = new test("Cristi");
echo $var->eat();
 
?>

You would get an error. That’s why you need to make use of $this->name;

This of it like passing parameters with $this.

__construct inside an object:

Example:

44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<?php
 
class eat{
	public $food;
 
	function __construct($food){
		$this->food = $food;
	}
 
	function echoes(){
		echo 'Cristi eats '. $this->food;	
	}
}
 
$obj = new eat("Banana");
echo $obj->echoes();
 
?>

As you see, you can create $this variables and use them in a further function of your class.

Public, private and protected.

If you declare a variable public, you can echo it like this:

45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<?php
 
class eat{
	public $food;
 
	function __construct($food){
		$this->food = $food;
	}
 
	function echoes(){
		echo 'Cristi eats '. $this->food;	
	}
 
 
}
 
$obj = new eat("Banana");
echo $obj->echoes();
echo $obj->food;
 
?>

Public, can be visible everywhere if you call it with the object: $obj->food or $obj->callit();
Private, can work only inside the current class.
Protected, can work inside other classes that extend the parent class.

Object inheritance or “extends”.

The syntax is this:

class eat2 extends eat{
}

so eat2 is the name of the second class and eat is the name of the parent class (the first one).

Now, if you just declare eat2{} with nothing inside it and you call functions like $obj2->do_something(); It will work because the do_something method (function) already exists inside the eat class (the first object).

Here is a full example:

46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<?php
 
class eat{
	public $food;
 
	function __construct($food){
		$this->food = $food;
	}
 
	public function echoes(){
		echo 'Cristi eats '. $this->food;	
	}
}
 
class eating extends eat{
 
}
 
$obj = new eating("Banana");
 
echo $obj->echoes();
 
?>

The inheritance system helps to write less code and have access to other functions from previous classes.

You can overwrite functions (methods) by just declaring them again in the second method (function).

Here is an example with overwritting a method:

47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
<?php
 
class eat{
	public $food;
 
	function __construct($food){
		$this->food = $food;
	}
 
	public function echoes(){
		echo 'Cristi eats '. $this->food;	
	}
 
 
}
 
class eating extends eat{
 
	function echoes(){
		echo 'Andrei eats ' .$this->food;	
	}
 
}
 
$obj = new eating("Banana");
 
echo $obj->echoes();
 
?>

An example with 3 classes:

48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
<?php
 
class eat{
	public $food;
 
	function __construct($food){
		$this->food = $food;
	}
 
	public function echoes(){
		echo 'Cristi eats '. $this->food;	
	}
 
 
}
 
class eating extends eat{
 
	function echoes(){
		echo 'Andrei eats ' .$this->food;	
	}
 
}
 
class eating2 extends eating{
 
}
 
$obj = new eating2("Banana");
 
echo $obj->echoes();
 
?>

The difference between functions and objects?

Think of it like this: the function is the engine and the object is the whole car.

A car needs an engine. You can group engines (functions) in an object to build a car. Interesting concept isn’t it?

__construct is called a magic method. You don’t want to create methods (functions) that start with __method_name.

The “final” keyword can be put for class or method. Like this. After that, you won’t be able to overwrite it with a new class or method.

Example.

49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
<?php
 
class help{
	final function hello(){
		echo 'hello';	
	}
 
}
 
class help2 extends help{
	function hello(){
		echo 'hello my friend';	
	}
}
 
 
$hello = new help();
 
echo $hello->hello();
 
?>

It will trigger an error.

You can’t declare variables (properties) as final.

While developing in php, you should always have the settings turned on to display errors. It’s much more easier to debug.

Put this code into your php to display all errors.

50
51
52
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

Generating an array inside a function:

51
52
53
54
55
56
57
58
59
60
61
62
63
<?php
function gen_one_to_three() {
    for ($i = 1; $i <= 3; $i++) {
        // Note that $i is preserved between yields.
        yield $i;
    }
}
 
$generator = gen_one_to_three();
foreach ($generator as $value) {
    echo "$value\n";
}
?>

If you use return instead of yield, it won’t work, you will get an error.
Also, you might see an error in your php ide program if you use yield. Ignore it.

References in PHP

References allows you to make two variables refer to the same content.
Here is an example:

52
53
54
55
56
57
58
59
60
<?php
 
$var = &$var2;
 
$var2 = 'x';
 
echo $var;
 
?>

Will return x because $var = $var2 actually.

Another example within a function:

53
54
55
56
57
58
59
60
61
62
63
<?php
 
$var2 = 'hello';
 
function help(&$var){
	echo $var;	
}
 
help($var2);
 
?>

It will return ‘hello’. If you don’t use the reference sign &, you will get the same result.

Division by zero.

You get this error if you try to divide a number to zero.

54
55
56
57
58
59
60
61
62
<?php
 
$var = 2;
 
$var = 2/0;
 
echo $var;
 
?>

Try to run 22/0 in the Windows calculator, you will get a similar error.

The easiest authentication you can make is with HTTP authentication with PHP: http://php.net/manual/en/features.http-auth.php

Uploading files within a form

“Be sure your file upload form has attribute enctype=”multipart/form-data” otherwise the file upload will not work.”

$_FILES contain all the data required.
$_FILES[‘input_name’][‘name’]; – name of the file that you uploaded.
$_FILES[‘input_name’][‘type’]; – type of the file that you uploaded.
$_FILES[‘input_name’][‘tmp_name’] – tmp name of the file from the server.
$_FILES[‘input_name’][‘size’] – size of the file.
$_FILES[‘input_name’][‘error’] – will display values like 0, 1, 2 etc, depending on the error, more information here: http://php.net/manual/en/features.file-upload.errors.php

Uploading multiple files in PHP example:

55
56
57
58
59
60
61
62
63
<?php
 
@$file1 = $_FILES['userfile']['name'][0];
@$file2 = $_FILES['userfile']['name'][1];
 
echo $file1;
echo $file2;
 
?>
56
57
58
59
60
<form action="" method="post" enctype="multipart/form-data">
  Send these files:<br />
  <input name="userfile[]" type="file" multiple="multiple"/><br />
  <input type="submit" value="Send files" />
</form>

Notice that multiple=”multiple” will allow the browser to select more than a file.
The concept is simple, it will upload an array. And you can tweak it further with php code.

The difference between mysqli_connect and new mysqli is that the first one is procedural programming while the second one is oop (notice the “new” syntax).

Examples:

mysqli_connect:

57
58
59
60
61
62
63
64
65
66
<?php
 
$db_server = 'localhost';
$db_user = 'root';
$db_password = '';
$db_name = 'aliendatatabase';
 
$connection = mysqli_connect($db_server, $db_user, $db_password, $db_name);
 
?>
58
59
60
61
62
63
64
65
66
67
<?php
 
$requestSQL = mysqli_query($connection, "SELECT * FROM vote order by id ASC LIMIT 1");
while ($row = mysqli_fetch_array($requestSQL)){
 
	echo $row['vote_option'];
 
}
 
?>

new mysqli:

59
60
61
62
63
64
65
66
67
68
<?php
 
$db_server = 'localhost';
$db_user = 'root';
$db_password = '';
$db_name = 'aliendatatabase';
 
$connection = new mysqli($db_server, $db_user, $db_password, $db_name);
 
?>
60
61
62
63
64
65
66
67
68
69
<?php
 
$requestSQL = $connection->query("SELECT * FROM vote order by id ASC LIMIT 1");
while ($row = mysqli_fetch_array($requestSQL)){
 
	echo $row['vote_option'];
 
}
 
?>

They both do the same thing and it should display the same thing.

And this is the PDO version.

61
62
63
64
65
66
67
68
69
70
<?php
 
$db_server = 'localhost';
$db_user = 'root';
$db_password = '';
$db_name = 'aliendatatabase';
 
$connection = new PDO("mysql:host=$db_server;dbname=$db_name", $db_user, $db_password);
 
?>
62
63
64
65
66
67
68
69
70
71
<?php
 
$requestSQL = $connection->query("SELECT * FROM vote order by id ASC LIMIT 1");
$counter=0;    //  Correct. 
while($row = $requestSQL->fetch(PDO::FETCH_BOTH)){
    $counter++; 
    echo $row['vote_option'];
}
 
?>

or you can use this simplified version:

63
64
65
66
67
68
69
70
71
72
<?php
 
$db_server = 'localhost';
$db_user = 'root';
$db_password = '';
$db_name = 'aliendatatabase';
 
$connection = new PDO("mysql:host=$db_server;dbname=$db_name", $db_user, $db_password);
 
?>
64
65
66
67
68
69
70
71
72
73
<?php
 
$requestSQL = $connection->query("SELECT * FROM vote order by id ASC LIMIT 1");
foreach ($requestSQL as $row){
 
	echo $row['vote_option'];
 
}
 
?>

since we all know that the result of the query is an actual array.

You can use this classic version with while also:

65
66
67
68
69
70
71
72
73
74
<?php
 
$db_server = 'localhost';
$db_user = 'root';
$db_password = '';
$db_name = 'aliendatatabase';
 
$connection = new PDO("mysql:host=$db_server;dbname=$db_name", $db_user, $db_password);
 
?>
66
67
68
69
70
71
72
73
74
75
<?php
 
$requestSQL = $connection->query("SELECT * FROM vote order by id ASC LIMIT 1");
while ($row = $requestSQL->fetch()){
 
	echo $row['vote_option'];
 
}
 
?>

To delete something with PDO:

67
$requestSQL = $connection->exec("DELETE FROM vote where id = '1' LIMIT 1");

An example with PDO prepare:

68
69
70
71
72
73
74
75
76
77
78
<?php
/* Execute a prepared statement by binding a variable and value */
$sth = $connection->prepare('SELECT *
    FROM vote
    WHERE id = :id LIMIT 1');
$sth->bindValue(':id', 2);
$sth->execute();
foreach ($sth as $row){
		echo $row['vote_option'];
}
?>

Another example for prepare:

69
70
71
72
73
74
75
76
77
78
79
80
81
<?php
 
$requestSQL = $connection->prepare("SELECT * FROM vote where id = '3' LIMIT 2");
$requestSQL->execute();
 
 
while ($row = $requestSQL->fetch()){
 
	echo $row['vote_option'];
 
}
 
?>

Another example:

70
71
72
73
74
75
76
77
78
79
80
81
<?php
 
$requestSQL = $connection->prepare("SELECT * FROM vote where id = '3' LIMIT 1");
$requestSQL->execute();
 
$requestSQL_result = $requestSQL->fetchAll();
foreach ($requestSQL_result as $row){
	echo $row['vote_option'];
}
 
 
?>

mysqli_fetch_row example:

71
72
73
74
75
76
77
78
79
80
<?php
 
$db_server = 'localhost';
$db_user = 'root';
$db_password = '';
$db_name = 'aliendatatabase';
 
$connection = mysqli_connect($db_server, $db_user, $db_password, $db_name);
 
?>
72
73
74
75
76
77
78
79
80
81
<?php
 
$requestSQL = mysqli_query($connection, "SELECT * FROM vote order by id ASC LIMIT 1");
while ($row =  mysqli_fetch_row($requestSQL)){
 
	echo $row[1];
 
}
 
?>

(mysqli_fetch_row) just grabs the data by array key, as you see “$row[‘1’]”.

The difference between mysqli_fetch_array and mysqli_fetch_assoc is simple.

Mysqli_fetch_array will return data if you call $row[‘name’] or $row[‘1’], considering that “name” comes after id in your sql table.
Mysqli_fetch_assoc will return data only if you call $row[‘name’] and it will return an error if you call $row[‘1’];

Get the number of days in a month:

$number = cal_days_in_month(CAL_GREGORIAN, 8, 2003); // 31

Converting strings to date:

73
74
75
76
<?php
$dt = new DateTime("2015-11-01 00:00:00");
echo "", $dt->format("y");
?>

You can assign other values like m, i etc. You can find all the syntax here: http://php.net/manual/ro/function.date.php

Adding days to a date example:

74
75
76
77
78
<?php
$date = date_create('08/30/2017');
date_add($date, date_interval_create_from_date_string('10 days'));
echo date_format($date, 'm/d/y');
?>

Careful about the syntax, it only works with slashes between day, month, year.

Creating date from string, procedural, easiest way.

75
76
77
78
<?php
$date = date_create_from_format('j-M-Y', '15-Feb-2017');
echo date_format($date, 'm/d/y');
?>

Calculating years between two dates:

76
77
78
79
80
81
<?php
$datetime1 = new DateTime('2017-08-30');
$datetime2 = new DateTime('1985-03-03');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%Y');
?>

Another example:

77
78
79
80
81
82
<?php
$datetime1 = new DateTime('2017-08-30');
$datetime2 = new DateTime('1985-03-03');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%m/%d/%Y');
?>

Another example of creating date from string. Notice that your initial string needs to separate month/day/year by lines or slashes (-/).

78
79
80
81
<?php
$date = date_create('2000/01/01');
echo date_format($date, 'm/d/Y H:i:s');
?>

Checkdate:

79
80
81
<?php
var_dump(checkdate(12, 51, 2000));
?>

Strtotime example:

80
81
82
83
84
85
86
<?php
$time = strtotime('03/03/1985');
 
$date = date('m/d/Y', $time);
 
echo $date;
?>

unlink = deletes a file.

Return a website in a single string:

81
82
83
84
<?php
$homepage = file_get_contents('https://incvice.com/');
echo $homepage;
?>

Reads the content of a txt file:

82
83
84
85
<?php
$homepage = file_get_contents('test.txt');
echo $homepage;
?>

Write inside a txt file:

83
84
85
86
<?php
$text = 'hello';
file_put_contents('text.txt', $text);
?>

Adding new line with file_put_contents:

84
85
86
87
88
89
90
<?php
 
$text = file_get_contents('text.txt');
 
$text .= "John Smith\n";
file_put_contents('text.txt', $text, FILE_APPEND);
?>

Get a website page within an array, using File:

84
85
86
87
88
<?php
$text = file('https://incvice.com/');
 
print_r($text);
?>

Filesize, filetype – to get info on a file.

Fopen will just open the connection to a file:

85
86
87
88
89
<?php
$text = fopen('text.txt', 'r');
 
echo $text;
?>

Example of fopen in action: (if the file is empty, you will get an error most likely).

86
87
88
89
90
91
92
<?php
$filename = 'text.txt';
$text = fopen($filename, 'r');
 
echo fread($text, filesize($filename));
fclose($text);
?>

This was also an example for fread. As you see, fread needs this syntax: ($text, filesize($filename));
Fread will always need fopen.

You can use fread only for files, not for websites.
For websites, you can use stream_get_contents.

87
88
89
90
91
92
93
<?php
$filename = 'https://incvice.com';
$text = fopen($filename, 'r');
 
echo stream_get_contents($text);
fclose($text);
?>

stream_get_contents does the same thing as file_get_contents but it only works in this syntax, with fopen.

move_uploaded_file – to move a file, upload a file.

To rename a file:

88
89
90
<?php
rename("text.txt", "text2.txt");
?>

To install a php library with composer.
Create a local folder in your wamp.
cmd > cmd to the location of the folder and type something like
composer require imdbphp/imdbphp

You can find libraries here: https://packagist.org

Curl stands for “Client URL Library”.

session_start actually starts or resumes a session.

Implode does the opposite of explode, it implodes array elements into a string.

Join (string function) does the same thing as implode.

similar_text is a function that will calculate the similarity between two strings and it will return percents.

str_repeat will just repeat a string: str_repeat(‘test’, 10); will echo test 10 times.

str_split can split a string into an array. str_split(‘hello’); will generate an array element for each letter, you can add str_split(‘hello’, 2); and it will generate array element each 2 letters.

wordwrap – you can insert a br for example after 20 characters, making the sentence on two lines.

Boolean means true or false.

var_dump, print_r will just display array content, it is related to arrays.

Add a comment: