PHP programming Ebook free download pdf pdf
PHP
PHP is one of the most widespread and effective programming languages for the WEB and it is also
very simple to understand. Moreover, we can find many free software to make the code we write run.
The file to program in php must always have php extension, and it also supports all HTML tags. This text is aimed at beginners, long and complex examples are not used in order to learn faster without detracting from the effectiveness of what you learn and also makes sure that even the explanations are not long and boring doing so the reader is put in a position to learn directly by programming, since I think that programming as everything is learned by practicing it.
All the examples in this text have been done to create safe and error-free examples.
INDEX
1 Variables
2 Arithmetic operators
3 Comparison operators
4 Instruction if
5 Instruction if else
6 Array
7 The increment operator
8 The decrease operator
9 The for cycle
10 The while loop
11 Instruction break
12 Instruction continue
13 Take the values from a form
14 Instruction switch
15 Logical operators
16 Instruction exit
17 The rand function
18 Pick up the date from the server
20 The function strlen
21 The foreach cycle
22 Instruction empty
23 Functions
24 Static Variables
25 The constants
26 Create a folder
27 Delete a folder
28 Take the IP address
29 Write and read files
30 Check to see if a file exists
31 Delete a file
32 Upload file
33 Session variables
34 Cookie
35 Turn characters into lowercase
36 Turn characters into uppercase
37 Format a number
38 Look for a value in an array
39 Instruction die
41 Look for a value in a tables of a DB
42 Insert a record
43 Change a record
44 Delete a record
1) Variables
Like all programming languages we find the variables, which are entities in which we will store our
data as numbers, alphanumeric characters, etc.In PHP to declare a variable, just precede it with the $ symbol. Example:
<?php $Nome = “Mario”; echo ($Nome); ?>
We have assigned to the variable Name the string Mario, if we make this piece of code we see that
the string will be printed.The strings must be enclosed in double quotes as in the example. Example 2:
<?php $Numero = 20;
?>
With the second example, we declared a variable and assigned it the value of 20, then with the echo
function we had it printed on screen.As for the assignment of a value to a variable, we can also declare a variable and then assign it a value later.
Example:
<?php $Nome; $Nome=Mario ?>
2) Arithmetic operators
The arithmetic operators as we all know are addition, subtraction, multiplication and division and
module. Let's see what the symbols are and how they are used in PHP.Sum of two numbers:
<?php
$Numero1=20; $Numero2=10; echo($Numero1 + $Numero2);
?> Division of two numbers:
<?php $Numero1=20; $Numero2=10; echo($Numero1 / $Numero2); ?>
Subtraction of two numbers:
<?php $Numero1=20; $Numero2=10; echo($Numero1 - $Numero2); ?>
Multiplication of two numbers:
<?php $Numero1=20; $Numero2=10; echo($Numero1 * $Numero2); ?>
Module between two numbers:
<?php $Numero1=20; $Numero2=10; echo($Numero1 % $Numero2); ?>
In this case 0 will be returned.
3)
Comparison operators
The comparison operators are used to compare two values and to see if they are equal or different in
this case see also which is the major or the minor.Their symbols are: Minor < Minor or equal <= Equal == Greater > Greater or equal >= Different != To check if two values are the same, the operator is double the same, to be careful because at the beginning one is often confused.
So how can we easily guess if we have two numbers such as 5 and 12 if we write:
5 <12 will be returned true, it will be true even if we write 5 <= 12 because the comparison says that
5 must be less than or even equal to 12 in this minor case and therefore returns true. The same thing for the greater and greater equal then: 12> 5 true; 12> = 5 true.As for the comparison the same if we write 5 == 5 will be true.
If we write 12! = 5, it will return true.
I can also compare two strings for example: $stringa1 = ”Ciao”; $stringa2 = “Buongiorno” If I write that: $stringa2 == $stringa2 it will be false instead $stringa1 != $stringa2 it will be true.
4) Instruction if
With the if statement we can have instructions executed or not based on whether the condition is true
or false.Example:
<?php $numero1=20; $numero2=10; if($numero1 == $numero2)
{ echo ("Istruzione eseguita"); } ?> Echo education will never be performed.
If instead: 5)
Instruction if else
With the addition of else we can make sure that if the expression is true, the statement that isimmediately after the if is executed, if it is false, the statement contained in the brackets of the else is
executed. Example:<?php $numero1=20; $numero2=10;
if($numero1 >= $numero2) { echo ("Prima stringa"); } else { echo("Seconda stringa"); } ?>
In this case it will appear "Prima stringa"
<?php $numero1=20; $numero2=10; if($numero1 == $numero2) { echo ("Prima stringa");
else { echo("Seconda stringa"); } ?>
In this case it will appear "Seconda stringa" 6)
Array Arrays are a collection of all of the same type, such as we can declare an array that contains 20 variables, but they are all of the same type.
To access an element of an array we use an index that indicates the position of the element. For
example, if we consider an array of 10 elements, the first element has index 0 while the last element
has index 9. Let's see how to declare uin array and how to use it. Example:<?php
$nomi=[10]; $nomi[0]="Gianni"; $nomi[1]="Giuseppe"; $nomi[3]="Mario"; echo ($nomi[0]." ".$nomi[1]); ?>
If we make the code written above the echo function will display the string Gianni and Giuseppe, in
fact they are the first and the second element.We can also use an array by directly assigning the values as in the following example:
<?php $Lista=array("Gianni", "Giuseppe", "Mario", "Michele"); echo ($Lista[0]." ".$Lista[1]." ".$Lista[2]." ".$Lista[3]); ?> If we execute the code, the four names inserted between the brackets will be written.
7)
The increment operator
The increment operator is used to increment number 1 every time a code is executed, this operator is
++ and we see how it is used.If we write:
<?php $Numero=3; $Numero++; echo("La variabile é stata incrementata di 1 infatti adesso il suo valore è: "); echo $Numero; ?> Then placing the ++ operator after the variable as in the example.
8)
The decrease operator
The decrement operator serves to decrease the value of a variable by 1 each time a code is executed,
this operator is - - and is used identically to the increment operator.Example:
<?php $Numero=3; $Numero- -; echo("La variabile é stata diminuita di 1 infatti adesso il suo valore è: "); echo $Numero; ?>
9)
The for cycle
The for loop as well as other types of cycles serve to perform an operation several times.They are useful when, for example, we go to read a file, then we can use a loop that starts at the beginning of the file and reads everything until the end of the file, scroll through the records of a database or scroll through the indexes of an array and more.
<?php for ($i=0; $i<=10; $i++) { echo($i."<br>"); } ?>
As we see the for loop between its parentheses we put a starting point that is 0, then the cycle
continues until the variable does not exceed the value 10, in fact it continues until the condition in the
second place of the brackets is true, and finally an increase to the variable that in this case is 1. By executing this cycle, the numbers 0 to 10 will be displayed. We can also give a different increase as in the following example:<?php for ($i=0; $i<=10; $i=$i+2) { echo($i."<br>"); }
Let's take a last example we apply a for loop to the array we have seen in the previous topic to display all the names:
<?php $Lista=array("Gianni", "Giuseppe", "Mario", "Michele"); for ($i=0; $i<4; $i++) { echo($Lista[$i]."<br>"); } ?>
10)
The while loop
The while loop as the for loop repeats one or more statements until the condition in parentheses becomes false.
In the while loop the increment of the variable we will go to insert it in the inside of the same loop as
we see in the following example:<?php $i=0; while($i<4) { echo($Lista[$i]."<br>"); $i++; } ?> We get the display of the names contained in the array.
Or let's take another example of a cycle that counts from 0 to 10:
<?php $i=0; while($i<=10) { echo($i."<br>"); $i++; } ?>
11) Instruction break
With the keyword break we can get out of a cycle before it ends, so that what happens is what we
have to do is put a condition that will get us out of the loop when we want, let's see an example<?php for($i=0; $i<=20; $i++) { echo($i); echo("<br>"); if($i==11) { break; } }
?>
If we execute the code above when the variable has the value 11, the break is executed, if instead we
try to insert the break instruction without delay, the cycle will never be executed.The same applies to the while loop, try to run the following code.
<?php $i=0; while ($i<20) { echo($i); echo("<br>"); if($i==11) { break; } $i++; } ?>
12)
Instruction continue
For example, if we are in a for loop and we want an instruction not to be executed if a certain
condition occurs, we can write a code as follows:<?php for ($i=0; $i<=10; $i++) { if($i==5) { continue; } echo($i); echo("<br>"); } ?> If we do the example above we see that the number 5 is not written.
13)
Take the values from a form
Now we will see how to get values from text boxes and some other input method and then pass them
to variables and then be able to process them.We begin to create an HTML form and insert two text boxes
<html> <body> <form action="input.php" method="post"> Inserisci qualcosa nelle caselle: <br><br> Casella 1: <input type="text" name="testo1"/> <br><br> Casella 2: <input type="text" name="testo2"/> <br><br> Seleziona qualcosa dalla casella: <select name="combo1"> <option value="val1">valore_1</option>
<option value="val2">Valore_2</option> <option value="val3">Valore_3</option> <option value="Val4">Valore_4</option> </select> <br><br> <input type="submit" value="OK"/> </form> <?php $variabile_1=$_POST["testo1"]; $variabile_2=$_POST["testo2"]; $variabile_3=$_POST["combo1"]; echo ("Il primo numero inserito è: ".$variabile_1); echo ("<br>"); echo ("Il secondo numero inserito è: ".$variabile_2); echo ("<br>"); echo ("Il valore selezionato è: ".$variabile_3); ?>
</html>
As we see in the example we have inserted two text boxes called testo1 and testo2, which then in the
code by their name we have inserted in the variables named variable_1 and variable_2 and in the same way to get the data from the combobox.14)
Instruction switch
With the switch we can run a series of comparisons and then run a command based on the result of comparisons. We see practically so we realize its operation.
<html> <body> <form action="input.php" method="post"> Seleziona qualcosa dalla casella: <select name="combo1">
<option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> <br><br> <input type="submit" value="OK"/> </form> <?php $variabile_1=$_POST["combo1"]; switch ($variabile_1) { case "1": echo ("Hai scelto il primo valore"); break; case "2": echo ("Hai scelto il secondo valore");
break; case "3": echo("Hai scelto il terzo valore"); break; default: echo ("Nessun valore scelto"); } ?> </body> </html>
As we see from the combobox we select an option and then it is passed to the variable, then the
inserted value is checked in the switch and the corresponding command is executed based on the
entered value, if the variable is empty or no comparison is true the default command is executed .
Let's take another example where the background color of the page is changed.<html> <body>
Seleziona il colore dalla casella: <select name="combo1"> <option value="1">Rosso</option> <option value="2">Verde</option> <option value="3">Blu</option> </select> <br><br> <input type="submit" value="OK"/> </form> <?php $variabile_1=$_POST["combo1"]; switch ($variabile_1) { case "1": echo ("<body bgcolor='#ff0000'>");
case "2": echo ("<body bgcolor='#00ff00'>"); break; case "3": echo("<body bgcolor='#0000ff'>"); break; default: echo ("Nessun valore scelto"); } ?> </body> </html>
15) Logical operators
With logical operators we can perform two or more comparing two or more expressions, they are the
AND, the OR, and the NOT.Their sibles are && for the AND, || for the OR and ! for the NOT.
AND operator Let's see how they work, then the AND operator when verifying two or more conditions returns true only if all conditions are true
<?php If (3<5 && 4>1 && 10<20) { echo ("I confronti sono tutti veri"); } else { echo ("I confronti sono falsi o almeno uno risulta falso"); } ?> If we make the list written above, the string will be written. Comparisons are both true.
If we try to change something, for example in the last comparison, we write that 10> 20 will come out of the string I confronti sono falsi o almeno uno risulta falso OR operator The OR operator returns true if at least one of the comparisons is true.
Then we see the following code:
<?php If (3<5 || 4<1 || 10>20) { echo ("Vi è almeno un confronto che risulta vero"); } else { echo ("I confronti risultano tutti falsi"); } ?>
In the example we said that 4 is less than 1 and 10 is greater than 20, but the total result is true
because we have remained that 3 is less than 5, if we try to change even the first putting 3 greater than
5 then they are all false then the string will appear and the comparisons are all false.NOT operator
The NOT operator inverts a result making it change from true to false and vceversa, in fact we try to
run the code that follows then rewrite it with the operator NOT and see how it changes.<?php If (5==5) { echo ("I due numeri sono uguali"); } else { echo ("I due numeri sono diversi"); } ?>
So far everything flows as written ie the string is printed I due numeri sono uguali
Now let's try to insert the NOT operator as follows, let's run the code and see that the result will say
I due numeri sono diversi<?php
If (!(5==5)) { echo ("I due numeri sono uguali"); } else { echo ("I due numeri sono diversi"); } ?>
16)
Instruction exit
With the exit keyword we can end the flow of a code, so if our program is running when it encounters
the keyword exit exits.
We have two examples that contain a cycle that counts from 0 to 20, the first we do not insert the exit
then print all the numbers on the page, while in the second code we insert the exit before the cycle and
we can see that the cycle will not be executed because the flow ends.<?php for ($i=0; $i<=10; $i++) { echo ($i.", "); } ?> The code written above will be executed.
<?php exit; for ($i=0; $i<=10; $i++) { echo ($i.", "); } ?>
in this code the loop is not executed because the exit will terminate the execution of the code.
17)
The rand function
The rand function allows you to print random numbers in a range chosen by us, in fact in the example
will be printed random numbers from 1 to 10, in the first function while the second will print numbers
from 4 to 50.In the brackets the first number indicates the first number from where to start and then the smallest and
the second number after the comma the maximum number.<?php $num=rand(1,10); echo($num); echo("<br>"); $num_2=rand(4,50); echo($num_2); ?>
18)
Pick up the date from the server
The function to get the date and date () we see in the example how it works.<?php echo date('d,m,Y'); ?>
In the brackets we have inserted 3 letters easily understand that d stands for the day, m stands for
month and Y stands for year. Let's try to change the order of the letters and see how the result changes,
for example:<?php echo date('m,d,Y'); ?> In this case month, day and year will be printed.
We can also assign the date to a variable by writing:
$data=date('d,m,Y'); echo($data); ?>
19) Verify a numeric value
To check if a value is numeric we use the function is_numeric () as in the following example:
<?php $num=25; if (is_numeric($num)) { echo "il valore è un numero"; } else {
} ?>
20) The function strlen
The strlen () function returns the number of characters in a string as we see in the example:
<?php $str="abcdef"; echo(strlen($str)); ?>
21) The foreach cycle
With the foreach loop we can take a value contained in a series of objects or an array and then either
display the whole or perform a search.In the following example we show all the contents of an array:
<?php $ar= array("Mario","Marco","Giovanni","Antonio", "Alfonso"); foreach($ar as $st) { echo($st); echo("<br>"); } echo("<br>"); ?> If we execute the code written above all the names inserted in the array will appear.
Now we carry out a search to find a specific name:
<?php $ar= array("Mario","Marco","Giovanni","Antonio", "Alfonso");
foreach($ar as $st) { if ($st=="Giovanni") { echo ($st); } } ?>
22) Instruction empty
With this function we can check whether a variable contains a value or after its declaration has not
yet been assigned a value, let's see how:<?php $nome;
if (empty($nome)) { echo ("La variabile nome è vuota"); } else { echo("La variabile nome contiene: ". $nome); } ?>
Let's try to give it a value such as Mario and see how the result changes as the following example:
<?php $nome = "Mario"; if (empty($nome)) { echo ("La variabile nome è vuota"); }
{ echo("La variabile nome contiene: ". $nome); } ?>
23)
Functions
A function is a code that is written somewhere in the script and is only executed when the function is
called.
The code written in a function can contain anything like calculations, work with strings, update files,
databases and more.
A function can return a value or do something inside it, in which we can pass values or call it only to
make the code inside it run.However with some examples everything will be easier to understand.
Let's do a simple function that calculates, for example, the air of a triangle passing it two parameters
that is the base and the height of the geometric figure in question.<?php
function calcola($base, $altezza) { $area=($base * $altezza)/2; return ($area); } ?> <?php $area_triangolo=calcola(3,4); echo ($area_triangolo); ?>
In the previous example the function calculates takes two parameters that are the base and the height
which are placed in the brackets when we call the function, and its result is inserted in the variable $
area_triangle. Let's do the same example with a function that does not return anything then:<?php function calcola ($base,$altezza) { $area=($base * $altezza)/2;
} ?> <?php calcola(5,4); ?>
In this case, the function does the same thing, however, it prints the result directly and therefore has no return value.
Let's take another example of a function that does not accept values and does not return any value, but
it shows a price list.<?php function listino_prezzi() { echo ("<table bgcolor='#33ddff' cellspacing='2' cellpading='2' border='1'>"); echo("<tr><td>Televisore </td> <td>marca XXXXX</td><td>42 pollici</td><td>Euro 200</td></tr>");
pollici</td><td>Euro 150</td><tr>"); echo("<tr><td>Videocamera </td><td>marca BBBBBB</td><td>caratteristiche MMMMMM</td><td>Euro 300</td></tr>"); echo("<tr><td>Lettore MP3 </td><td>marca ZZZZZZ</td><td>8 Gb Stereo</td><td>Euro 80</td></tr></table>"); } ?> <?php listino_prezzi(); ?>
However the code was written with each instruction on a line as in the following figure, in fact for
reasons of space the code in the text went to the end.24)
Static Variables
The static statement makes sure that when we have a variable in a script such as a function such a variable when the function finishes executing what the contained value should do for example as a result inserted into a variable we lose.
Often there may be cases in which the value of a result must be preserved and to make this happen we
must declare a static variable and therefore in its declaration make it precede the static keyword.Let's take some examples and see how it works right away.
<?php function conta() { for ($i=0; $i<10; $i++) { $numero=0; $numero++; } echo ($numero); }
?> <?php conta(); conta(); ?>
In this example the function is called twice but will give the same value because it starts again from
scratch in the following example instead it maintains its value and is incremented further.<?php function conta() { for ($i=0; $i<10; $i++) { static $numero=0; $numero++; } echo ("<br>" . $numero); }
?> <?php conta(); conta(); ?>
25) The constants
Una costante è una variabile che una volta che gli abbiamo assegnato un valore essa non può più
cambiare, vale sia per le stringhe che per altri valori numerici ecc.Il suo uso è molto semplice come nell'esempio che segue:
<?php DEFINE("numero",10); DEFINE("nome","Marco"); echo (numero);
echo("<br>"); echo (nome); ?>
26) Create a folder
The function to create a folder is mkdir ("Folder name") and then insert the name of the folder to be
created between the brackets. But you have to be careful because if you try to create a folder that already exists and then as we know two folders with the same name can not exist in the same direction we get an error.
Then in the code that follows we see that we use a condition that verifies the existence of the folder
we want to create and then if the folder does not exist we are going to create otherwise the warning
appears.<?php if (!(is_dir("Foto"))) { mkdir("Foto");
} else { echo("La cartella esite"); } ?>
27) Delete a folder
Referring to the previous example, if we want to delete the created folder we will write:
<?php rmdir("Foto"); ?>28) Take the IP address
Taking a user's IP address is very simple: just apply the following code:
<?php $ip = $_SERVER['REMOTE_ADDR']; echo(“il tuo IP è: “ . $ip); ?> We insert the IP into the variable $ ip, and then print it on the screen.
29) Write and read files
To write to a file we use the fopen () function which opens a file if it exists or creates it if it does not
exist. In the brackets we insert the name of the file to be opened and the mode of access to the file,that is, in read or write and read mode. Once the file is open, we will write it with fwrite (), and once
the writing operation is finished, we will close it as in the following example:<?php $txt = fopen("Testo.txt", "w+"); fwrite($txt, "Questa stringa viene scritta nel file"); fclose($txt); echo ("Scrittira completa con successo"); ?>
With w + the file is opened if it exists otherwise it is created and inserts the string, but if we want to
add a new string this option does not allow it every time the data is written replacing everything inthe file, if instead we want adding a new data without deleting what is already written we replace the
w + with "a".Let's run the code that follows and see that what we want to insert is added.
<?php $txt = fopen("Testo.txt", "a+"); fwrite($txt, "Questa stringa viene aggiunta nel file"); fclose($txt);
echo ("Scrittira completa con successo"); ?>
As we noted in the insertion, the string is inserted on the same line if instead we want to add to the
fwrite () characters to start a new line ie: fwrite ($ txt, "This string is added in the file". "\ R \ n "),
then when we're going to create a file in which we plan to add data in a new line and always add commands to create a new line.READ A FILE
To read a text file we use a while loop to scroll through the file to the end. And the fgets function to
read the lines as follows.<?php $leggi = fopen("Testo.txt","r"); while (!feof($leggi)) { echo fgets($leggi); echo("<br>"); } fclose($leggi); ?>
30)
Check to see if a file exists
Now that we have seen how to create, read and write to a file, let's see how to check if a file exists.
Then:
<?php if (file_exists("Testo.txt")){ echo("Il file esiste"); } else { echo "Il file non esiste!"; } ?>
So from how you can easily guess the written code if the file exists we do an operation otherwise we
do another.31) Delete a file
To delete a file we simply use the unlink () statement in the brackets to insert the file name to be
deleted as follows:<?php if (file_exists("Testo.txt")) { unlink("Testo.txt"); echo("Il file è stato eliminato"); } else { echo "Attenzione: il file non esiste!"; } ?>
We check if the file exists and if it exists we delete it, otherwise we warn that the file does not exist.
32)
Upload file
To transfer a file from a computer to the server we write two pages one in html and give it a name for
example formFile.html and the other a page in php we will call upload.php or a name you want.Nella pagina html inseriamo il form come segue:
<html> <body> <form action='upload.php' enctype='multipart/form-data' method='post'> <input type='file' name='upload'/> <input type='submit' name='carica' value='Carica File'/>
</form> </body> </html>
This form assumes that the php page is called unpload.php otherwise in the action tag you have to
enter the name you have chosen for the page otherwise an error occurs because the page is not found.
The PHP code is as follows:
<?php if ($_POST['carica']){ move_uploaded_file($_FILES["upload"]["tmp_name"], $_FILES["upload"]["name"]); echo("File caricato "); } ?>
we can also check if the file already exists in the direction with the function we have seen previously
and therefore does not perform the operation, let's see how:if ($_POST['carica']) { $File=$_FILES["upload"]["name"]; if(file_exists($File)) { echo("Il file esiste già nella direzione"); exit; } move_uploaded_file($_FILES["upload"]["tmp_name"], $_FILES["upload"]["name"]); echo("File caricato "); } ?>
33) Session variables
want to bring a value from one page to another we must use other methods and then session variables
which store the values on the server allowing to transport the values we enter from one side of the site to the other.Once a session variable has been created, we assign the value to it. This value keeps it stored until we close the browser.
Their use is not complex at all. So to give an example we insert two pages we will call Session and Session2, logically they are names that we have put in this way to stay on the subject otherwise you can use any name for the pages that does not affect at all with the variables in question. On the first page we insert:
<?php session_start(); $_SESSION["nome"]="Mario"; $_SESSION["cognome"]="Rossi"; echo($_SESSION["nome"] . " " . $_SESSION["cognome"]); echo("<br><br><a href='Session2.php'>vai al file 2</a>"); ?>
First we started the session with session_start () and then we can declare variables by giving them a
name and a random surname that we then print on video, and then inserted the link with the second page in which we will write:<?php session_start(); echo("Le variabili di sessioni contengono: " . $_SESSION["nome"] . " " . $_SESSION["cognome"]); ?>
34) Cookie
We have seen how to transport data from one part of a website with session variables to another, another way to store data in order to use it from any part of a website is to write cookies.
Let's take an example so you can see practically everything.
<?php
setcookie("nome", "Mario", time() +3600); echo ("<a href='cok2.php'>vai a pagina 2</>"); ?>
The first parameter in brackets is the name of the cookie, the second is the value to be stored while
the third parameter sets the duration of the cookie in seconds, so the cookie we wrote after 3600 can
no longer display the data entered. At this point we see how to withdraw the entered value:<?php $nome = $_COOKIE["nome"]; echo $nome; ?> if we run this code, obviously after setting the cookie will display the string Mario.
Obviously the instruction to read the cookie as above we can insert it in any page of the site. To delete a cookie, which in this case what we have created, we write the following:
<?php setcookie("nome","",time() -3600); ?>
From how we see we assign a null string to the data and then set the time with a negative value.
Example.
<?php $testo="ABCDEF"; echo(strtolower($testo)); ?>
36)
Turn characters into uppercase To transform a string of uppercase characters we use the strtoupper () function Example.
<?php $testo="abcdef"; echo(strtoupper($testo)); ?>
37) Format a number
first is the number to be formatted, the second represents the number of decimal places, the third is the
decimal separator and the fourth separates every three digits of the whole part.Example:
<?php $num=2300000; $num2 = number_format($num, 2, ',', '.'); echo($num2); ?>
In this case the function returns the number so formatted 2,300,000.00, so that not only is it more professional to present a number as written above, but above all it is more readable.
38)
Look for a value in an array make an example directly as it is a very simple instruction to use.
<?php $persone=array("Marco", "Pietro", "Franco", "Roberto", "Giovanna"); if (in_array("Giovanna", $persone)) { echo("Nome trovato"); } else { echo("Esito ricerca negativo"); } ?>
39) Instruction die
The die instruction is similar to exit, so when we want to interrupt the flow of the program we can use
that instruction.<?php echo ("Questa riga viene eseguita"); die("<br>Dopo di questa istruzione il flusso termina"); echo ("Codice seguente"); ?>
40)
Interact with databases
Now that we have learned a sufficient amount of commands to create a website, in this last part we see how to interact with a MySQL database, and then add, modify, delete and read data from a table of a DB. We begin to create a table in MySQL called Subscribers, as fields we enter ID, name, surname, city (we write city without accent) and insert fill some records so that in the first example we will see how to connect to a database and pull out some data. Done when said, in the code that follows we set up a connection to the DB and then we go to give some examples on how to get the data out.
For those who have already been able to execute instructions in SQL everything will be easier, but
Then:
<?php $connection = mysql_connect('localhost','root','digilander'); mysql_select_db('DB2',$connection); $query = "SELECT * from Iscritti"; $risultato = mysql_query($query, $connection) or die("Errore..."); $numrows = mysql_num_rows($risultato); if ($numrows==0){ echo ("Attenzione nessun dato trovato"); } else { for($i=0; $i<$numrows; $i++){