Download as pdf
Download as pdf
You are on page 1of 639
PHP CAR Cours & Exercices Da PHP & MYSQL: Courses and corrected exercises Master dynamic web development Maximilien Lambert Copyright © 2024 No reproduction, storage in a retrieval system or transmission in any form whatsoever may be made without the prior written permission of the publisher, except for brief quotations incorporated in critical articles or reviews. Every effort has been made to ensure the accuracy of the information presented in this book. However, the examples contained in this book are provided functional at the time of writing in the context of specific browser versions and current PHP and MySQL versions. Neither the author, nor the publisher, nor their distributors and resellers can be held responsible for any direct or indirect damage resulting from this book. Author : Maximilien Lambert Publisher: Maximilien Lambert Production Designer: Elise Dubois First publication: April 2024 www.skilldeve.com About the author ‘Maximilien Lambert is an experienced web developer and trainer in the field of digital technologies. With his recognized expertise, he has led numerous international training courses and seminars at world- renowned institutions. His exceptional pedagogical approach has earned him a reputation for excellence among his students, thanks to his ability to simplify complex concepts and make them accessible to all. A university lecturer for over 20 years, Maximilien Lambert shares his passion for learning and passing on IT knowledge. His long experience in the educational field enables him to inspire several generations of learners around the world, passing on not only technical skills, but also a global vision of the web development sector. Passionate about sharing knowledge, Maximilien Lambert excels at imparting computer skills, inspiring generations of learners around the world. In addition to his teaching activities, he offers specialized training to professionals, helping them hone their skills and stay at the cutting edge of their respective fields. His dedication to excellence, his passion for teaching and his technical expertise make Maximilien Lambert an essential reference in the field of web development and digital trai Table of contents About the author Foreword Introduction and development environment SECTION A: MASTER THE FUNDAMENTALS OF PHP PROGRAMMING Chapter 1 Variables, constants and operators Chapter 2 Conditional structures Chapter 3 Loops in PHP Chapter 4 Functions and Generators in PHP Chapter 5 Tables in PHP Chapter 6 PHP built-in functions SECTION B ADVANCED DATA MANAGEMENT AND BROWSER INTERACTION Chapter 7 Browser data processing (GET, POST) Chapter 8 Images and files Chapter 9 Session and cookie management SECTION C MYSQL DATABASE MANAGEMENT Chapter 10 Introduction to Databases and Connecting to a MySQL Database Chapter 11 Inserting, retrieving and displaying data from a database Chapter 12 U and deleting data ina database SECTION D WEB APPLICATION SECURITY Chapter 13 PHP security : Attack prevention and risk management SECTION E OBJECT-ORIENTED PROGRAMMING IN PHP Chapter 14 Classes and objects Chapter 15 Data Encapsulation and Modeling Chapter 16 Inheritance in PHP Chapter 17 Interfaces and abstract classes Chapter 18 Exception handling Chapter 19 Namespaces Chapter 20 Traits Chapter 21 Magic methods Exercises correction Encouragement and Congratulations About the author Foreword In an ever-changing digital world, mastering web programming languages like PHP and manipulating databases like MySQL are crucial skills for any budding web developer. Our book "PHP & MySQL: Master dynamic web development" has been meticulously designed to guide you through every stage of your learning process, from beginner to advanced levels. SECTION A : Mastering the fundamentals of PHP programming In this first section, we delve into the heart of PHP programming, exploring variables, constants, operators, conditional structures, loops, functions and arrays. You'll discover how to manipulate data, control program flow and organize your code efficiently. SECTION B: Advanced data management and browser interaction Section B takes you further into dynamic web development by teaching you how to interact with browsers. You'll learn how to manage data from forms, manipulate images and files, and set up sessions and cookies to create interactive user experiences. SECTION C: MySQl database management Database managementis an essential aspect of web development. In this section, you'll learn how todesign and manipulate MySQL databases, from connecting to a database to inserting, retrieving, updating and deleting data. SECTION D : Web Application Security Web application security is of paramount importance. This chapter will provide you with the knowledge you need to secure your PHP applications against common attacks such as SQL injection, Cross-Site Scripting (XSS) and Cross-Site Request Forgery (CSRF). SECTION E: Object-oriented programming in PHP Object-oriented programming (00?) is a powerful paradigm that allows you to structure your code in a modular and reusable way. In this section, you'll discover the fundamental concepts of OOP, including classes, objects, encapsulation, inheritance, interfaces, abstract classes, exceptions, namespaces and traits. Each chapter is illustrated with numerous examples, accompanied by simple, detailed explanations. Some chapters are accompanied by practical exercises to put your knowledge into practice, and tohelp you check your understanding, a suggested correction for each exercise is provided at the end of the book. We're confident that this book will provide you with the tools you need to become a competent and accomplished PHP developer. Whether you're a beginner looking to learn new skills, or an experienced professional looking to deepen your knowledge, "PHP & MySQL: Master dynamic web development" is your ideal companion on your learning journey. Happy reading and learning! The editorial team You can count on our support! Ifyou have any questions about any aspect of this book, or if you need any help, please send us an e-mail at contact @skilldeve.com and mention the title of the book in the subject line. Share your opinion We look forward to hearing from you! After exploring the pages of "Mastering HTML and CSS: from beginner to expert", we encourage you to share your opinion. To do so, simply click on the following link to access Amazon's review page dedicated to this book. Your feedback is valuable, not only to us, but tothe entire technology community. Your feedback will help us keep the quality of our content at an optimum level. We look forward to reading your thoughts and hearing how this book has enriched your knowledge of HTMLand css. What bonuses await you in this book? Access to a private community dedicated to web development, where you can communicate and ask all your questions. Scan the QR below to access it. Link: https://www.skilldeve.com/community/dveloppement-web/join Introduction and development environment In this introductory chapter, we will delve into the fascinating world of web development with PHP and MySQL. We will start with an exploration of how websites work, examining the differences between static and dynamic sites, as well as the programming languages associated with each type. Then, we will focus on the development environment for coding in PHP, including setting up a local Apache server and MySQL for creating and testing web applications on our own machine, How does a website work? When it comes to how a website works, it's common to distinguish between two main types: static and dynamic. Before going into detail, it’s important to clarify the two essential components: the client, which corresponds to the user's computer, and the server, which hosts the website. The fundamental question is: How do these two players communicate with each other? To answer this question, we need to examine the communication process specific to each type of website. In the case of a static website, communication takes place in two simple steps: + Theclient sends a request to the server to display a web page; The server responds by sending the requested web page back to the client. In concrete terms, in this scenario, the server stores web pages as static files and sends them to clients without any further modification or processing. For a dynamic site, on the other hand, the process is slightly more complex, with an intermediate step: The client sends a request to the server to display a web page; Instead of simply returning an existing page, the server dynamically generates the page according to the client's specific request; The server then sends the freshly generated page to the client. In this case, the server performs real-time processing and calculations to create a personalized page for each client request. In conclusion, the fundamental difference between static and dynamic sites lies in the way web pages are generated and delivered to users, with significant implications in terms of data processing and content personalization. 4) Request LET} generation Response Programming languages for every type of website Websites fall into two broad categories: static and dynamic. Each type of site uses specific programming languages for its development. Static websites : Static websites are mainly built using markup languages such as HTML (HyperText Markup Language) and 88 (Cascading Style Sheets). HTML is used to structure the content of a Web page, defining elements such as headings, paragraphs, images, etc. CSS is used to style and format these elements, controlling their visual appearance. Dynamic Websites : Dynamic websites require interaction with a database, and use server-side programming languages to generate personalized content based on user requests. Common programming languages used for dynamic web development include PHP (Hypertext Preprocessor), Python, ASP .NET, Java, JavaScript and Ruby, and many others. PHP is one of the most popular languages for server-side web development, due to its simplicity, flexibility and compatibility with many database management systems, notably MySQL. Python and Ruby are also widely used for their dynamic web development capabilities and expressive syntax. Understanding the programming languages suitable for each type of website is essential for choosing the most appropriate technology for a specific project, and for developing robust, functional websites. Development environment There are two main approaches to website development: Local development : This method involves working on one’s own computer, using a specific development environment to create and test the website, Once development is complete, the site is then transferred to a remote hosting server to make it accessible over the Internet. This approach is often preferred, as it offers an isolated working environment and does not require a permanent Internet connection. In this book, we explore in detail how to set up this development environment. Remote development : With this approach, website development takes place directly on the remote server hosting the site under development. This method is suitable for experienced developers working on complex projects requiring real-time collaboration with other team members. It also enables the site to be tested on different browsers and operating systems before going into production. In short, the choice between local and remote development depends on the specific needs of the project, the experience of the developer and the resources available. All the examples presented in this book are tested locally before being deployed on a remote server. To develop a dynamic website, several elements are required on our machine: “Apache server: This is the Web server responsible for managing the site. However, by default, Apache can only handle static websites, i.e. HTML pages. To enable it to handle PHP as well, a plugin must be added. By combining Apache with PHP, our computer will be able to read web pages written in PHP. Database management system (DBMS): Since dynamic websites require interaction with databases, a database management tool is essential. MySQL is one of the most commonly used DBMS for this purpose. Fortunately, there are software programs that make it much easier to install these items on your computer. Depending on the operating system you're using, you can choose from the following options: + For Windows: WAMP Server (http://www.wampserver.com/) For Mac: MAMP (https://www.mamp info/en/downloads/) + For Linux: XAMPP (https://www-apachefriends.org/fr/download.html) XAMPP is available in three different versions: one for Windows, one for Mac and one for Linux. Although it is more complete than the other options (WAMP and LAMP), itis not necessary to use all its features. In this book, welll be installing XAMPP for its versatility. However, you are free to choose between XAMPP, MAMP or WAMB, as the basic operation is the same for all three. Downloading and installing XAMPP on Mac OS Here are the steps to download and install XAMPP on macOS: Visit the official Apache Friends website: https://www.apachefriends.org/fr/download. html On the download page, you'll see different versions of XAMPP available. Choose the one best suited to macOS by clicking on the corresponding download button. 15 apechettiends orgytr/downioed htm 02.12/PHP 8212 Version 8.0.28/ PHP 8.028 0.17 / PHI 7 a24senpa2s Contens md shat Pas Pré-requis Plus de téléchargements » « XAMPP pour OS X 8.0.28, 8.1.17 & 8.2.4 code do ‘ame conten end chat EEEEIIEY sco mw conan ena chet ERIE 151 cones end shat EERIE so system. It supports intel (x64) or Apple M1 (arm64) CPUs, Once the download is complete, open the downloaded file (it should be in your Mac's "Downloads" folder). Double-click on the installation file to begin the XAMPP installation process. Follow the on-screen instructions to install XAMPP on your Mac. You may need to enter your administrator password to authorize installation. eco (xampp xampp-05x-8.0.28-0- installer When youclick on the XAMPPicon, an alert window may appear, telling you that "macOS cannot check this app for malware". In this case, depending on the version of your Mac system, you may need to modify your Mac's security settings in order to be able to install KAMP : + Open System Settings. + Click on Privacy & Security, scroll down and click on the "Open anyway" button to confirm your intention to open or install the app. nechercher OF icons Ase urtogcte sapere @ aur Baivercon GQ sereae Bw Grctiticatons Bsn GB concentration By ter0s stern B centre de contre ‘Aaoriser es apotiations taléchargées depuis xo» Store 0 Lie Store ot es Svelppeurs identities Leuteaton e « xampp-oe18.0.28-0.ratater» ost logue car Fapplcation proven ‘um develosces non cen ‘Oumr quand mime ‘Aerie es accesses 8 Demande our es nowwenu accessores & Flevast pete. When installation is complete, you'll see a confirmation window. Click on "Finish" to close the installer. XAMPP is now installed on your Mac. To start the services (Apache, MySQL, etc.), open XAMPP from your "applications" folder and run the "manager-osx" file, then click on the corresponding buttons to activate the necessary services. e XAMPP 8.1.17-0 ] Welcome Manage Servers Server Events j Serer sae © Mysat Database Running Start © ProFTPO Stopped oe | @ Apache Web Server Running Restart Configure Start All ‘Stop All Restart All Once the services are started, you can access the XAMPP management interface via your web browser by entering "localhost" in the address bar. These steps should allow you to successfully download and install XAMPP on your Mac. Downloading and installing XAMPP on Windows Here are the steps to download and install XAMPP on Windows: Visit the official Apache Friends website: https://www.apachefriends.org/fr/download.html On the download page, you'll see different versions of XAMPP available. Choose the one best suited to Windows by clicking on the corresponding download button. Once the download is complete, open the downloaded file by double-clicking on it. It should be in the folder where you normally download files. The XAMPP installer will open. Click "Yes" if Windows asks you to authorize changes on your computer. The installer will guide you through the installation process. Choose the components you wish to install (by default, they are all selected) and select the folder where you wish to install XAMPP. Click on the "Install" button to begin installation. Wait for the process to complete. Once installation is complete, you will be prompted to start XAMPP components (Apache, MySQL, etc.). Click on "Finish" to close the installer. XAMPPis now installed on your computer. To start the services, open XAMPP from the Start menu and click on the corresponding buttons to start Apache and MySQL. Once the services have been started, you can access the XAMPP management interface via your web browser by entering "localhost" in the address bar. These steps should enable you to download and install KAMPP successfully on your Windows computer. Download and install a text editor After installing XAMPP, we recommend you download and install a text editor for writing and editing your code files. Here are a few examples of the most popular text editors suitable for web development: Sublime Text: Sublime Text is a lightweight, highly customizable text editor with many useful features for web development, such as syntax highlighting, auto-completion and project management. Download link: https://www.sublimetext.com/ Visual Studio Code: Visual Studio Code (VS Code) is a source code editor developed by Microsoft. It is extensible, offers Git integration, debugging features and numerous extensions for web development. Download link: https://code.visualstudio.com/ Brackets: Brackets is an open-source text editor developed by Adobe. It is specially designed for web development and includes features such as live preview, syntax highlighting, auto-completion and extension support. ittps://brackets.io/ Download link: You can choose the text editor that best suits your web development needs and preferences. Once you've installed your preferred text editor, you can start creating and editing code files for your web project. Creating a project in XAMPP In XAMPP, you don't create projects directly, but rather create directories for your projects in the htdocs directory. Here's how to doit: Find the htdocs directory: The htdocs directory is where you store your website files. By default, this directory is located in the XAMPP installation folder. On Windows, it's usually located in C:\xampp\htdocs, and on Mac, it's in /Applications/KAMPP/htdocs. Create a new directory for your project: In the htdocs directory, create a new directory for your project. You can give it any name you like, e.g. "ebookphp’, Once you've created the directory for your project, you can place all your website files and folders in it. This can include HTML, CSS, PHP, JavaScript files, images, etc. Accessing your project via the browser: Once you've placed your project files in the directory you've created, you can access your website by opening a web browser and entering the following URL in the address bar: http://localhost/ebookphp. Be sure to replace "ebookphp" with the name of the directory you've created for your project. By following these steps, you can create and access your project in XAMPP. Make sure you start the Apache and MySQL services in XAMPP so that your website functions correctly. Your first PHP script Here are the steps to create your first PHP script using XAMPP and the "ebookphp" directory created in the “htdocs' folder: Launch XAMPP as explained above and start Apache by clicking on the corresponding "Start" button. Make sure they are displayed in green, indicating that it is running. Open the text editor of your choice to write your PHP script. In your text editor, create anew file and save it in the "ebookphp' directory located in the "htdocs' folder of your XAMPP installation. Name this file "first_script.php". Write your First PHP Seri Once you've written your PHP script, save the file. Launch your favorite web browser (e.g. Google Chrome, Mozilla Firefox, etc.) In your browser's address bar, enter the following URL: http://localhost/ebookphp/premier_script.php and press "Enter" You should see the phrase "Hello, world!" displayed in your browser, indicating that your first PHP script has been successfully executed. @OS = @ localhost/ebookphp/first_scr x + € > CG @® localhost/ebookphp/first_script.php Hello, world! Congratulations! You've just created and executed your first PHP script using XAMPP. This simple example marks the start of your journey into the exciting world of web development with PHP. Error display ‘As you know, making errors, especially syntax errors, is quite common, and Ican assure you that there isn't a developer in the world who doesn't make them. It's therefore very useful to display indications of these errors. In fact, depending on the configuration of your server, errors may not be displayed at all! Many beginners find themselves puzzled when they run a PHP page in a browser and see absolutely nothing. There's no error message, just a blank page, for example. This happens when errors are present in the code and our PHP server is not configured to display errors. To solve this problem, simply make a few changes to XAMPP's php.ini file. To find the location of this file, simply addition the code below to the previously created file first_script.php (or any other file in your project). , ete.) and logical operators (&&, ||, !). Using variables: Best practices for naming and using variables in PHP, as well as managing their scope and handling in scripts. String concatenation: How to combine and manipulate strings in PHP using the concatenation operator (.) to create more complex strings. Notion of data types: An introduction to the different data types in PHP, such as integers, floating-point numbers, strings, arrays, ete. The concept of type conversion: How to convert data from one type to another in PHP, especially between numeric and string types. Using constants : The definition and use of constants in PHP to store values that do not change throughout script execution. Increment and decrement operators: Use the increment (++) and decrement (--) operators to modify the value of a numerical variable. Special assignment operators: The syntax of combined assignment operators such as. perform arithmetic operations and update the value of a variable in a single step. etc, to By covering these aspects, youl have a complete and in-depth understanding of variables, expressions and operators in PHE, which will help you write efficient and functional PHP scripts. Introduction to variables and constants in PHP PHP programming is based on the use of variables and constants to store and manipulate data. In this chapter, welll explore in detail these two fundamental concepts and their use in the development of dynamic web applications. Imagine you're a magician and you've got a magic box. This box can hold all sorts of different things. You can put rabbits, coins, doves and so on inside. At any time, youcan change what you put in your hat. It's like a variable in PHP where you can store different values and change them to suit your needs. Now imagine you have a treasure chest containing your most precious treasures. This chest is solid and indestructible, and it always contains the same precious treasures, no matter what's going on around it. It's like a constant in PHP where you define a value that will never change. Defining variables and constants in PHP In PHP, a variable is a named storage space that can contain a value that can be modified throughout script execution. It is defined by a name followed by an equal sign (=) and the assigned value. For example: "; $varl = "Hello everybody" echo $varl; // Display "Hello" echo "
"; echo $var2; // Display "Hello" echo "
"; Result: In this example, $var2 is assigned by value to $var1, which means that $var2 contains a copy of the value of $var1. Consequently, when the value of $varl is modified, this does not affect the value of $var2. eee @ localhost/ebookphp/ x + € > CG © localhost/ebookphp/ Hello Hello everybody! Hello Assignment by reference : Conversely, when a variable is assigned by reference using the "&" symbol, both variables share the same reference to the memory location containing the value. This means that any modification made to one of the variables also affects the other, as they point to the same value in memory. This allows data to be shared and manipulated directly between the variables, which can be useful in certain use cases. Example: "; $varl = "Hello"; echo $var2; // Display "Hello" In this example, $var? is assigned by reference to $varl, which means that both variables point to the same value in memory. So, when the value of $var1 is modified, the value of $var2 is also modified, as they share the same reference. Result: @O8e@ @ localhost/ebookphp/ x € © © localhost/ebookphp/ Hello Hello everybody! Using variables in PHP scripts Variables can be used in PHP scripts simply by referencing their name. They can be used to display data, perform calculations, or any other operation requiring the manipulation of data. Here are a few examples of how variables can be used in PHP scripts: Example 1: - In this example, the variables $firstname and $age are used to store information about a person, then displayed ina sentence. Result ece @ localhost/ebookphp/ x + € > G_ @ localhost/ebookphp/ Hello, my name is Alice and I am 25 years old. Example 3: © — @ localhost/ebookphp/ The sum of 10 and 5 is equal to 15. Display and concatenation in PHP In PHP, text and variables can be displayed in a number of ways, such as using the echo function or enclosing strings in double ("") or single (*') quotation marks. Concatenation in PHP consists in joining several strings to form a single string. This can be useful when you want to combine variables, constants and text strings to form a complete message or a more complex expression. Example of the use of double and single quotation marks : "; echo'Hello, $firstname!; // Display "Hello, $firstname!" Result: @ OO @ localhost/ebookphp/ x ie € >» © — @® localhost/ebookphp/ Hello, Alice! Hello, $firstname! In this example, the first echo statement uses double quotes to display the value of the variable $firstname, while the second echo statement uses single quotes, displaying the literal text "$firstname" without interpreting the variable. Use of the concatenation operator, the dot (.): In PHE, the concatenation operator is represented by the dot (.) and is used to concatenate strings. $name ~ "Smith"; ‘$message = "Hello, ". $firstname."". $name ."!"; echo $message; In this example, the variables $firstname and $lastname contain the values "Alice" and "Dupont" respectively. The concatenation operator (,) is used to combine these variables with text strings to form the complete message "Hello, Alice Smith!". Double quotation marks ("" ), separated by a space and inserted between the two variables $firstname and $lastname, create a space between the values of these two variables (between Alice and Dupont). Result: @O8@ @ localhost/ebookphp/ x + € » G_— @ localhost/ebookphp/ Hello, Alice Smith ! Example2 ‘ G © bocathostjebookphp/ She's turning 30 next week, but she doesn't look a day over 25 Apostrophe in a string with a contraction Let's modify the previous example by using apostrophes instead of double quotes: Shp Sage = 30; $message - ‘She's turning" Sage. "next week, but she doesn't look a day over 25'; echo $message; When you run this code, youll get an error because of the line where the variable $message is defined. OOOO vethonieooncne! */_ « © © Locamostjebookhoy Parse error: syntax error, unexpected identifier *s* in /Application/X AMPP/xamppfiles/htdocs/ebookphp/index php on line 3 The error occurs because the apostrophe is used in the string “She's” and “doesn't”. In PHP, when a string is enclosed in single quotes (*"), apostrophes within the string must be escaped with a backslash (\) to avoid confusion with the end of the string. To resolve this error, you can escape the apostrophe with a backslash (\): ‘ // Display current PHP version echo PHP_OS."
; // Display operating system name echo PHP_INT_MAX."
'; // Display the maximum value of an integer on a given platform echo _FILE__.*
'; // Display the absolute path of the file echo_LINE_."
*;// Display current line number > Executing this code gives you a result similar to the following output specific to our machine's data. @ OS @ localhost/ebookphp/index..p/ x — + € % CG — @ \ocalhost/ebookphp/index..php 8.1.17 Darwin 9223372036854775807 /Applications/XAMPP/xamppfiles/htdocs/ebookphp/index..php 21 8.1.17: is the PHP version installed on our computer + Darwin: the Mac operating system for our machine + 92233372036854775807 : is the maximum number on the 64-bit platform + /Application/X AMPP/xamppfiles/htdocs/ebookphp/index.php :is the absolute path of the file currently being run + 21 :is the line number corresponding to the echo __LINE__ instruction; Comparing variables and constants Variables and constants are fundamental elements of PHP programming, but they differ in their behavior and use: Variables can be modified and reassigned during script execution, while constants retain their immutable value. Variables are declared using the § sign, while constants are declared using define() or const. Constants are often used for values that remain constant throughout the script, such as tax rates or mathematical constants, while variables are used for values that may change during script execution. Data types in PHP In PHP, data can be of different types, each with its own characteristics and uses. Data types in PHP can be divided into two main categories: primitive data types and complex data types. For the purposes of this first chapter, it's important to understand the different primitive data types that PHP supports. These data types are used to store different values in variables. Primitive data types in PHP Primitive data types in PHP are basic data types that represent simple values. Here are the main primitive data types in PHP: Integers (int): Integers are used to represent whole numbers, such as -1, 0, 1, 2, etc. They can be positive or negative. They can be positive or negative. Float numbers : Float numbers are used to represent decimal numbers, such as 3.14, -0.5, 1.618 and soon. Strings: quotation marks. For example: $name = ‘John’, Booleans (bool): These represent truth values, either true or false. For example: $is_true = true}. ‘The “null” type is used to represent the absence of a value. This is different from an empty string", an integer 0, or a Boolean false. In other words, the variable containing null contains no useful data or information. It's an indication that the variable is empty or has not yet been defined with a valid value. ‘hese represent a sequence of characters enclosed in single ('') or double ("" ) To retrieve the data type of a given variable, you can use the gettype() function natively defined in PHP. Example: <2php Declaration and initialization of variables different value: $age = 30;// An integer $price ~ 19.99; // A loating-point umber $name = john’ // A character string $message = "John is 20!;// Another string $is_true = true; // A Boolean (true) $is_false = false; // A Boolean (false) $salary = null; // No value is assigned to the variable // Display the data typeof each variable echo gettype( Sage). "
"; // Display “integer echo gettype($price)."
';// Display “double echo gettype( $name). "
// Display "string” echo gettype($message). "
"; // Display “string echo gettype($is_true)
"; // Display "boolean echo gettype( is false). *cbr>' // Display "boolean* echo gettype( salary) ."
*; // Display "NULL" The code in this example uses the gettype() function to get the data type of each variable, then uses echo to display each data type with a
tag to jump to the next line in the HTML output. Finally, the code output will be something like thi @ OS @ bocalhosyebookphp/index.' x + € © © Localhost/ebookphp/index..php integer double string string boolean boolean NULL Note that there are other variable types, such as arrays and objects, which are considered complex types. Welll look at these variable types in more detail in later sections of this book. It's also important to note that unlike other strongly typed programming languages, where we have to explicitly declare the type of each variable, in PHP the type of a variable is determined automatically according to the value assigned to it. For example, if we declare $age = 17;, this means that the type of variable $age is an integer. PHP operators PHP operators are special symbols used to perform operations on variables and values. They play an essential role in data manipulation and in controlling the execution flow of PHP scripts. Operators can be used to perform mathematical calculations, compare values, assign values to variables, concatenate strings and much more. In PHP, operators are classified into different types according to their functionality: arithmetic operators, assignment operators, comparison operators, logical operators and increment/decrement operators. In what follows, we'll explore each type of operator, explaining its use, its syntax rules and providing practical examples to illustrate how it works. Understanding operators is essential to writing efficient and functional PHP scripts. Arithmetic operators Arithmetic operators are used to perform mathematical operations on numerical values. The following table illustrates the main arithmetic operators in PHP. Operators ‘Name ‘Example + |Addition $a+$b - ‘subtraction $a-$b * Multiplication i$a* $b / (Division $a/$b % Modulos $a.% $b = 'Exponentiation $a" $b Addition (+): The Addition operator (+) is used to addition two or more numerical values together. For example, if you have two variables $a and $b, $a + $b will give the sum of these two variables. Subtraction (-): The subtraction operator (-) is used to subtract one numerical value from another. For example, if you have two variables $a and $b, $a - $b will give the difference between these two variables. Multiplication (*): The multiplication operator () is used to multiply two numerical values together. For example, if you have two variables $a and $b, $a* $b will give the product of these two variables. Division (/): The division operator (/) is used to divide one numerical value by another. For example, if you have two variables fa and $b, $a / $b will give the quotient of the division of $a by $b. Modulo (%): The modulo (%) operator is used to obtain the remainder of the division of one numerical value by another. For example, if you have two variables $a and $b, $2 % $b will give the remainder of the division of $a by $b. Exponentiation (**): The “ operator is the exponentiation operator in PHP. It is used to raise a value to a given power. For example, if you have a value $a and you want to raise it to the power $b, you can use the ** operator like this: $a $b. This is equivalent to raising $a to the power $b. For example, if $a is 2 and $b is 3, then $a $b will give 8, because 2 raised to the power of 3 equals 8. This operator is very useful for performing calculations involving powers in your PHP scripts. ‘These arithmetic operators are used in mathematical expressions to perform numerical calculations in PHP scripts. They are essential for performing a variety of mathematical operations in your programs. Example: <2php. // Declaration of variables $a- 10; $b=3; 1 Addition $addition = $a + $b; echo "Addition: addition
"; //subtraction $subtraction = $a- $b; echo "subtraction : $subtraction
's // Multiplication $multiplcation - $a* fb; echo "Multiplication : ¢multiplication
"; // Division $division = $a / $b; echo "Division: $division
"; / Modulo $modulo = $2% $b; echo "Modulo: $modulo
"; //Exponentiation $exponentiation - $a" $b; echo “Exponentiation : exponentiation
"; > Result: @ OS @ Locathost/ebookphp/ x + € % G © lbocalhost/ebookphp/ Modulo : 1 Exponentiation : 1000 In this example, variables $a and $b are set to 10 and 3 respectively. Arithmetic operations are then performed with these values: Adding $a and $b gives 13 (10 + 3). Subtracting $b from $a gives 7 (10 - 3). Multiplying $a and $b gives 30 (10 * 3). Dividing $a by $b gives approximately 3.33333 (10/3). The modulo of $a by $b gives 1, which is the remainder of the Euclidean division of 10 by 3. Finally, $a raised to the power $b gives 1000 (10** 3). Assignment operators ‘Assignment operators are used to assign values to variables. The following table illustrates the main assignment operators in PHP: Simple assignment operator (=): This operator is used to assign a value to a variable. For example, $a = 10; assigns the value 10 to variable $a. Combined assignment operators: These operators combine an arithmetic operation with the assignment operation. For example, the += operator additions the right-hand value to the left-hand variable and assigns the result to the left-hand variable. So $a += 5; is equivalent to $a = $a + 5; Other combined assignment operators: Other combined assignment operators include - which work ina similar way to subtract, multiply, divide and get the remainder respectively. (Operators Use [Meaning = $a=$b |Assigning the value lof $b to the variable ga + fa+= $b $a =$a+ $b b= $a-= $b fa=$a-$b re $a*= $b $a = $a" $b ve fa/= $b a= $a/$b = $a %= $b $a =$a% $b n= fa $b $a=$argb = a= $b fa=$a.$b Examples: "; ww equal to 10 // Combined assignment operators $b=5; $b echo"\$b after applying the +- operator: $b
"; j/ Equals $b = $b + 3 and the new value of $bis 8 $e $e echo"\$e after operator =: $e
"; 2; //Equals $c ~ $c- 2 and the new value of $bis 6 $d=6; $d" 4; //Equals $d = $44 and the new value of $b is 24 echo"\$d after applying the *= operator: $d
"; % $e. echo"\$e after applying the /= operator: $e
"; Bh Equals $e = $e /3 and thenew value of $bis 4 $= 10; $£%- 3; // Equivalent to $f ~ $£% 3 and the new value of $bis 1 $f
"; echo"\$f after applying operator > Execution of this code displays the new values of variables $a, $b, $c, $d, $e and $f after applying the corresponding operators: OOS @ localhost/ebookphp/ x + € > G © localhost/ebookphp/ $a after simple assignment operator: 10 $b after applying the += operator: 8 $c after operator $d after applying the *= operator: 24 $e after applying the /= operator: 4 $f after applying operator %= : 1 Combined assignment operator .= This operator is used to concatenate a string with another existing string, then assign the result to the variable to the left of the operator. For example, if you have a variable $message containing a string "Hello", and you want to addition "world!" to this string, you can use the .= operator like this: ‘"; echo"\$messagel after &= and.= operators: $message
"; > In this example, the variable $message1 is declared and initialized with the string "Hello". By using the reference assignment operator (&=), the $message2 variable is assigned the same value as the $message! variable. Next, the string "world!" is concatenated to the variable $message? using the concatenation operator .= , which also modifies the value of $message2. But the value of $message1 is also modified, since $message1 and $message? are linked by reference. Execution of this code produces the following result: @ OS @ localhost/ebookphp/ x € 2% G_— @® localhost/ebookphp/ $message? after applying the &= and = operators: Hello monde ! $message! after &= and = operators: Hello monde ! Comparison operators Comparison operators in PHP are used to compare variable values and produce a Boolean result (true or false) based on the comparison. The following table illustrates the main comparison operators available in PHP. [Operators Use Meaning p= lfa==$b | Checks if the values of $a and $b are equal regardless of type Checks whether the two values are equal and of the same type l= I$a!= $b Checks if the two values are different regardless of type <> lfa<> $b [Sameroleas!= 'gal==$b | Checks if two values are different or of different types le ga<$b Checks if $a is less than $b > lga> $b Checks if $a is greater than $b <= ga<= $b Checks if $a is less than or equal to $b >= $a>=$b | Checks if $a is greater than or equal to $b Examples of equality operators: In this example, the value that will be stored in variable $result is "true", as variables $a and $b are equal in terms of value. If yourun this code, you'll get the value 1 as the value of variable $result, which corresponds to the Boolean value true. However, if you replace the (==) operator with the (===) operator, code execution will display 0, which corresponds to the Boolean value false of the $result variable. ) comparison operator: Compares two expressions. Returns- , 0 or 1 depending on whether the first expression is less than, equal to or greater than the second. Example: $b}; $result2 = ($a <=> $c); echo fresulti; echo"
"; echo $result2; Running this code displays: + The value 1 for $result1 because the value of $a is much greater than that of $b. + The value -1 for $result2 because the value of $a is less than that of $c. In summary, comparison operators in PHP are used to compare variable values and produce a Boolean result (true or false) based on the comparison. They can be used to verify equality, difference, superiority, inferiority and other comparisons between values. The main comparison operators include ==, ===, !=, = and <=>, They are essential for evaluating conditions and making decisions in PHP scripts. Logic operators Logical operators in PHP are used to combine or invert Boolean expressions (true or false). As you'll see in the rest of this book, these operators are often used to create complex conditions by combining several logical expressions. The following table illustrates the main logical operators available in PHP : symbol [Use Meaning | lopera-|s tors [$a && $b | AND: Returns true if $a and $b are true (true) (oR ll I$all$b | OR: Returns true if at least $a or $b istrue. XOR \XOR |$aXOR Returns true if only $ais true or if is only $bis true Denial |! $a, Returns the inverse of a boolean expression AND operator (&& or and): The AND operator returns true if all Boolean expressions combined are true. True && True gives True True && False gives False False && True gives False False && False gives False Example: 2; $b=5<1 Sresult = ($a &6 $b); // $result is fals echo fresult; because fb is false In this code, we have two comparison expressions: $= 10> 2;: This expression compares whether 10 is greater than 2. As this is the case, $a takes the Boolean value true. $b = 5 < 1;: This expression compares whether S is less than 1. Since this is not the case, $b takes the Boolean value false. Then we have a third expression that uses the logical operator && (AND) to combine the Boolean values of §aand $b: $result = ($2 && $b); // fresult is false because $b is false The && (AND) operator returns true only if both expressions combined are true. In this case, since $a is true and $bis false, $result takes the Boolean value false. Finally, executing this code displays the value of $result using the echo function, which displays false because $result is false. ‘OR operator (|| or or): The OR operator returns true if at least one of the combined Boolean expressions is true. + True || True gives True + True || False gives True + False ||True gives True + False || False gives False Example: -2; $b=5<1; $result = ($a ll $b); // $result is false because $b is false echo $result; In this code, variables $a and $b respectively store the expressions 10 > 2 and 5 < 1 from the previous example. However, $result = ($a || $b); uses the logical operator || (OR) to combine the Boolean values of $a and $b. Since fais true and §b is false, the expression $a || $b evaluates to true. Thus, the variable fresult takes the value true. Execution of this code displays the value of the $result variable, which is 1 (true) because $result contains the value true. XOR (exclusive OR) operator: is a logical operator used to evaluate Boolean expressions. XOR returns true (or 1) ifone and only one of the expressions is true, but not both at the same time. If both expressions are true or false, XOR returns false (or 0). In summary, XOR can be represented by the following truth table: + True XOR True gives False + True XOR False gives True + False XOR True gives True + False XOR False gives False In programming terms, the XOR operator is often used to perform comparison operations requiring a condition where only one of the expressions must be true for the result to be true. Example: / Definition of variables // Use the XOR operator in an expression $result = ($x < 8 XOR $y > 5}; // Display result echo result; // Display "0" (false) because both expressions are true In this example, the expression $x < 8 is false because $x has a value of 20, and the expression $y > 5 is true because $y has a value of 10. Since only one of the two expressions is true, the result of the XOR operation will be true, represented by 1 in PHP. Operator ! (NOT): is a logical unary operator that inverts the result of a Boolean expression. It is used to negate or invert the Boolean value of an expression. Here's a summary with an example: Definition of variables $x=20; Sexpressiont = ($x> $y); Sexpression2 - !$expression1; In this code, we have two variables $x and $y which contain the values 20 and 10 respectively. Next, we have an expression $expression1 that compares $x to $y using the > comparison operator. Since §xis 20 and $y is 10, the expression $x > $y will be true, so expression! will evaluate to true. Finally, we have a second expression $expression2 which uses the ! (NOT) operator to invert the result of $expression1. As $expression1 is true, the “!” operator converts it to false, so $expression2 will evaluate tofalse, In short, after executing this code, $expression1 will be true and expression? will be false. Increment and decrement operators Increment and decrement operators are used to increase or decrease the value of a numerical variable in a more concise and efficient way. Increment operator "++" The "++" operator is used to increase the value of a numeric variable by 1. Example: In this example, we have a variable $x initialized to the value 5. Next, we use the "++" increment operator prefixed (++$x) on the $x variable. The prefixed increment operator (before the variable) increases the value of $x by 1, then returns this new value. So, even before display, the value of $x is increased by 1, from 5 to 6. In short, the ++$x operation first increments the value of $x by 1, then displays this new value on the screen. Example of suffixed use: On the other hand, if we put the ++ operator after the variable $x, execution of the following code displays 5 (the value of $x:is first displayed, then increased).

You might also like