PHP programming from scratch tutorial. Learning PHP and MySQL the Right Way


The Internet in the modern world occupies an increasingly strong position. About 15 years ago, access to the network required expensive equipment and a lot of money to pay bills. Now anyone who has at least a mobile phone can get on the Internet for a penny. More and more services and services are moving to electronic form. From a means of communication and information exchange, the Internet is turning into a convenient tool for doing business and making money.

Every day, millions of users visit their favorite sites, download mail, files or news, play online games, conduct company business or just chat, blog and forums. Most of these users have never thought about how it all works, who creates new sites and services, how and with what.

This electronic textbook is intended for those who simply surf the Web is not enough. For those who want to learn how to create their own websites and be on the wave of the latest trends in programming and design.

General principles

Before you start learning a language, you need to unequivocally determine the terminology and understanding of the general principles of the Internet. Let's start with the principles of the network and sites.

The Internet network consists of a huge number of interconnected computers, routers and other hardware needed for proper operation. Each element of the Internet (node) has a unique descriptor - an IP address. Knowing the IP address of the node, you can try to connect to it, and with a little skill, you can determine who this address belongs to and in which region of the world it is located. IP addresses are usually written as four groups of numbers separated by dots, for example

192.168.100.003 or 10.10.0.123

Agree, remembering the addresses of all frequently visited pages is not an easy task. Therefore, there are special DNS (Domain Name Resolution) servers on the Internet, which store lists of mapping IP addresses and symbolic names. It is thanks to these servers that the user always gets to the desired IP address by typing only the name of the page in the browser.

After we have entered the name of the desired page into the browser line, the browser independently obtains the IP address of the desired server from DNS and sends a special request to receive the page (HTTP request) to this address. A specialized program running on the server (the so-called Web server) processes this request and returns the required page to the browser.

Obviously, all page rendering actions can be unambiguously divided into two categories: those performed on the client side ( client code or front-end) and executed on the server side ( server code or back-end). Moreover, the server does not know anything about the current state of the client, and the client knows nothing about the current state of the server. When developing exchange algorithms, you must always keep this in mind and transmit the necessary data in a timely manner, describing the state or the required action.

Depending on the place of application, the means of implementing the parts also differ. On the client side, typically only HTML, JavaScript (AJAX), CSS, and Flash are used. Back-end developers are less constrained in terms of funds, because most existing languages ​​allow you to create or describe HTML pages. The most widely used now are Java, Perl, PHP, Python, Ruby, C# and VB.NET. Each of them has its strengths and weaknesses, so the developer must make a choice based on the tasks before him.

Why PHP?

There are a large number of languages ​​that can be used when creating websites. Some languages ​​have been around for a long time and are successfully used (or no longer used). Some languages ​​are still very young and have not yet received wide distribution. Recently, PHP has become one of the leaders in popularity, for several reasons:

  1. Simplicity. The language is very easy to understand, especially for novice programmers.
  2. Development speed. Due to its simplicity and intuitiveness, PHP allows you to create quite complex sites very quickly.
  3. Availability of libraries There are a huge number of ready-made examples and class libraries. Hundreds of libraries have been created and tested, greatly simplifying the life of a developer.
  4. Support Almost every server on the internet supports PHP
  5. Security PHP allows you to create truly secure sites thanks to built-in support for data encryption during storage and transmission.

However, PHP pays for its benefits with some limitations. For example, using PHP to access system functions is very inconvenient compared to Perl or Python (which is why many sysadmins love Perl so much). There are a few more limitations that we'll talk about in the relevant sections.

1. Befriend the PHP Reference

If you're new to PHP, then it's time to check out the awesome PHP reference. The PHP Reference is incredibly comprehensive and has really helpful comments on every article. Before you ask questions or try to solve the problem yourself, save time and just head for the guide. The answers to your questions are already conveniently placed in a useful article on the PHP.net site.
In this case, we recommend that you look for reference books in Russian on your own, preferably php for beginners. We will be glad if you give a link to useful reference books in the comments to the article (Just keep in mind that this is a translation of the article).

2. Turn on error reporting

6. Indent and use spaces for readability

If you don't use indentation and whitespace in your code, the result looks like a painting by Jackson Pollack. Make sure your code is readable and searchable, because you will almost certainly make changes to it in the future. IDEs and modern text editors can automatically indent code.

7. Make your code layered

Tiering your applications is nothing more than splitting the various components of your code into parts. In the future, this will give you the ability to easily change the code.

8. Always use

Often programmers try to use abbreviations in PHP statements. Here's how it's usually done:

<% echo "Hello world"; %>

echo "Hello world" ;

<% echo "Hello world" ; %>

While this does save a few characters, these methods are all deprecated and unofficial. stick to the standard, as it is guaranteed to be supported in all future versions.

9. Use meaningful, consistent titles

Naming is not just for your own pleasure. There is nothing worse than tearing through another programmer's meaningless conventions. Help yourself and others by using meaningful names for your classes and properties.

10. Comment, comment, comment

In addition to using spaces and indentation to separate code, you will also need to use inline comments to annotate your code. You'll thank yourself later when you have to go back and look up something in the code, or if you just don't remember what a certain function did. It's also useful for those who need to review your code.

11. Install MAMP/WAMP

MySQL is the most popular kind of database used with PHP (though not the only one). If you need to set up a local environment for developing and testing your PHP applications on your computer, consider installing MAMP (Mac) or WAMP (Windows). Installing MySQL on your own computer can be a tedious process, and both of these software packages contain MySQL. Smart and simple.

12. Set Limits on Your Scripts

Setting a time limit for PHP scripts is a very responsible thing. There are times when scripts break, and when that happens, you'll have to use the set_time_limit property to avoid endless loops and database connection timeouts. Set_time_limit sets a time limit for the maximum number of seconds a script will run in (default 30). After this time, a fatal error is raised.

13. Use objects (or OOP)

Object-oriented programming (OOP) uses objects to represent the components of an application. OOP is not only a way to break up your code into separate logical sections, it also reduces code repetition and makes it much easier to modify it in the future.

14. Understand the difference between single and double quotes

Using single quotes in strings is more efficient because the parser doesn't have to sift through the code looking for special characters and other things that double quotes allow. Where possible, try to always use single quotes.

Objection: Actually, this is not necessarily true. Benchmark tests show that when testing strings without variables, there are some performance benefits to using double quotes.

15. Don't put phpinfo() in your webroot

Phpinfo is a wonderful thing. By simply creating a PHP file that has:

and by attaching it somewhere on the server, you can instantly know everything about your server environment. However, many beginners will place a file containing phpinfo() in the webroot of the server. This is an extremely insecure practice, and if someone with an inquisitive mind gains access, they could potentially jinx your server. Make sure phpinfo() is in a safe place, and as an extra measure, remove it once you're done.

16. Never, ever trust your users

If your application has places for users to log in, you should always assume that someone will try to enter a questionable code. (We're not implying that your users are bad people. It's just common sense.) A great way to keep your site safe from hackers is to always initialize your variables to protect your site from XSS attacks. PHP.net has an example of a properly closed form with initialized variables:

if (correct_user ($_POST [ "user" ] , $_POST [ "password" ] ) (

$login = true ;

if ($login) (

forward_to_secure_environment();

17. Keep passwords encrypted

Many newbies to PHP often dump sensitive data like passwords into the database without using encryption. Consider using MD5 to encrypt passwords before sharing their database.

echo md5("myPassword"); // renders-

echo md5("myPassword") ; // renders-

Objection: However, remember that MD5 hashes have been compromised for a long time. Of course, they are more secure than not, but with the help of a giant "spectral table" hackers can recover your hash. For even more security, consider adding "salt" (white noise interference). "Salt" is usually an extra set of characters that you append to a custom string.

18. Use database visualization tools

If you find it difficult to plan and modify databases for your PHP applications, you might consider using a database visualization tool. MySQL users can work with DBDesigner and MySQL Workbench to visually design their databases.

19. Use Output Buffering

Output buffering is an easy way to greatly improve the quality and speed of your PHP script. Without output buffering, your script will render the HTML on the page as it is processed - in chunks. Adding output buffering allows PHP to store the HTML as a variable and send it to the browser in one chunk.

To activate the output buffering function, simply add ob_start() like this at the beginning of the file.

Objection: While not required, it's generally considered good practice to just stick with the “ob_end_flush();” function. towards the end of the document. P.S. Do you also want to compress HTML? Just change "ob_start();" to "ob_start('ob_gzhandler')";

XHTML

untitled

untitled

20. Protect Your Script From SQL Injection Attack

If you do not escape characters used in SQL strings, your code is vulnerable to an SQL injection attack. This can be avoided by using either the mysql_real_escape_string function or prepared SQL statements.

Here is an example of mysql_real_escape_string in action:

$username = mysql_real_escape_string($GET["username"]);

$username = mysql_real_escape_string ($GET [ "username" ] ) ;

And a prepared statement:

21. Try an ORM

If you are writing object-oriented PHP, you can use OR-mapping (ORM). An ORM allows you to convert data between relational databases and object-oriented programming languages. In short, an ORM makes it possible to work with databases in the same way that you work with classes and objects in PHP.

There are many ORM libraries for PHP such as Propel, and ORM is built into PHP frameworks such as CakePHP.

22. Cache Database Driven Pages

Caching database-driven PHP pages is a great idea to improve the loading speed and performance of your script. It's really not that hard to create and retrieve static content files with our good friend ob_start(). Here is an example taken from Snipe.net:

// TOP of your script $cachefile = "cache/".basename($_SERVER["SCRIPT_URI"]); $cachetime = 120 * 60; // 2 hours // Serve from the cache if it is younger than $cachetime if (file_exists($cachefile) && (time() - $cachetime< filemtime($cachefile))) { include($cachefile); echo ""; exit; ) ob_start(); // start the output buffer // Your normal PHP script and HTML content here // BOTTOM of your script $fp = fopen($cachefile, "w"); // open the cache file for writing fwrite($fp, ob_get_contents()); // save the contents of output buffer to the file fclose($fp); // close the file ob_end_flush(); // Send the output to the browser

// TOP of your script

$cachefile = "cache/" . basename ($_SERVER [ "SCRIPT_URI" ] ) ;

$cachetime = 120 * 60 ; // 2 hours

// Serve from the cache if it is younger than $cachetime

if (file_exists ($cachefile ) && (time () - $cachetime< filemtime ($cachefile ) ) ) {

include($cachefile) ;

I present to your attention a free translation of the article 30+ PHP Best Practices for Beginners

PHP is the most widely used programming language for the web. Here are thirty top tips for beginners to help you get the basics right.

1. Befriend the PHP Manual

If you are a PHP beginner, then it's time to check out the amazing PHP tutorial. The PHP manual is incredibly complete and has really helpful comments on every article. Before asking questions or trying to solve the problem yourself, go straight to the manual. There is a good chance that the answer to your question is already contained in articles on the PHP.net site.

2. Turn on error output

6. Use indentation and spaces for readability

If you do not use indents and spaces in the code, the result looks like the art of Jackson Pollack (an American artist, ideologue and leader of abstract expressionism, who had a significant impact on the art of the second half of the 20th century). Make sure that your code is readable and easy to find the right piece of code in it, because you will most likely need to refine it in the future. IDEs and advanced text editors can indent automatically.

7. Step up your code

This means nothing more than separating different code components into separate parts. This will make it easy to change the code in the future.

8. Always use

Oftentimes, programmers try to use a shorthand form for declaring PHP scripts. Here are some examples:

<% echo "Hello world"; %>

Although this shortens the notation by a few characters, all of these methods remain for compatibility and are unofficial. stick to the standardthis will guarantee support in all future versions.

9. Use meaningful names, following naming conventions

Naming is not just for your benefit. There is nothing worse than trying to find something in meaningless variable names. Help yourself and others by using meaningful names for your classes and functions.

10. Comments, Comments, Comments

Apart from using indentation and code separation, you can also use comments to describe your code. You'll thank yourself later when you need to go back and look up something in the code, or when you can't remember what a certain function does. It will also be useful to anyone who will view your code.

11. Install MAMP/WAMP

MySQL is the most popular database server used with PHP (if not the only one). If you want to set up a local development environment for testing your PHP applications, take a look at MAMP (Mac) or WAMP (Windows). Installing MySQL on your computer can be quite a tedious process, and both of these packages already contain MySQL. Clean and simple.

12. Limit your scripts

It's good practice to set a time limit for your PHP scripts. There are times when a script fails, and if it does, you might want to use a script time limit to prevent errors related to infinite loops and database connection timeouts. set_time_limit allows you to set a limit on the script execution time in seconds (by default, this value is 30). After this time is exceeded, a fatal error is generated.

13. Use objects (or OOP)

14. Distinguish between double and single quotes

It is most efficient to use single quotes in strings where you don't need to parse "escaped" characters and other things that might be contained in double quotes. Use single quotes wherever possible

Note: This is not really true. Tests show that if a string contains no variables, then double quotes give a performance gain.

15. Don't put phpinfo() in your server root directory

(displays information about the PHP interpreter) this is a wonderful thing. Create a simple PHP file with this content

and put it somewhere on the server, you can see comprehensive information about your server. However, many beginners place the file containing phpinfo() in the root directory of the web server. This is really not safe, seeing information about the server can potentially harm him. Make sure phpinfo() is in a safe place, or better yet, remove it.

16. Never trust users

If your application has fields for user input, then you must assume that the user will try to enter dangerous code. (This doesn't mean all users are malicious. It's just better to think so.) To avoid hacking attempts, always try to initialize your variables with the following lines.

17. Keep passwords encrypted

Many novice PHP programmers store sensitive data in the database, such as passwords, in clear text. Let's see how to use MD5 to encrypt passwords before writing them to the database.

echo md5("myPassword"); // prints -

Note: Keep in mind that MD5 hashes have already been cracked. They add security, but an attacker can decrypt the hash using rainbow tables. For added security, add "salt" (salt). "Salt" adds additional characters to the user string.

18. Use database visualization tools

If you're having trouble executing and modifying data in PHP while working with a database, try using the visuals. MySQL users can use DBDesigner and MySQL Workbench to display data in the database.

19. Use Buffered Output

Buffered output is an easy way to improve the performance of your PHP scripts. Without buffered output, your scripts render HTML in chunks. By adding buffered output, PHP saves the HTML code as a variable and outputs it to the browser in one chunk.

To enable output buffering, simply add ob_start() at the beginning of the file.

Note: It's considered good practice to add the ob_end_flush() function; to the end of the document. P.S. Want to compress HTML? Just replace ob_start(); on ob_start("ob_gzhandler");

For more information go here

untitled

20. Protect scripts from SQL injections

If you don't use character escaping in terms with SQL queries, then your application is susceptible to SQL injection. You can avoid this by using mysql_real_escape_string , or prepared (precompiled) queries.

Mysql_real_escape_string example:

$username = mysql_real_escape_string($GET["username"]);

and the prepared line:

$id = $_GET["id"]; $statement = $connection->prepare("SELECT * FROM tbl_members WHERE id = ?"); $statement->bind_param("i", $id); $statement->execute();

By using prepared constructs, we prevent user data from being directly written into the query. Instead, we use the "bind_param" method to bind values ​​to variables in the query. More secure, faster, especially when executing multiple CRUD statements at a time.

21. Use an ORM

If you are writing object-oriented code in PHP, you can use object-relational mapping (ORM). ORM allows you to convert data between a relational database and an object-oriented programming language. In short: ORM allows you to work with the database in the same way as with classes and objects in PHP.

One of the many ORM libraries for PHP Propel, and ORM is also present in PHP frameworks such as CakePHP.

22. Cache pages that use the database

Caching pages that use the database reduces the load and improves the performance of the script. This allows you to create and use static files using the ob_start() function. Example from Snipe.net:

// script start $cachefile = "cache/".basename($_SERVER["SCRIPT_URI"]); $cachetime = 120 * 60; // 2 hours // use cache if value is less than $cachetime if (file_exists($cachefile) && (time() - $cachetime< filemtime($cachefile))) { include($cachefile); echo ""; exit; ) ob_start(); // start buffered output // your script and HTML should be here // end of script $fp = fopen($cachefile, "w"); // open cache file for writing fwrite($ fp, ob_get_contents()); // save buffered output content to file fclose($fp); // close file ob_end_flush(); // send data to browser

This piece of code uses the cached version of the page, unless the page is "older" than 2 hours.

23. Use caching systems

If you want to use a more secure caching system than the script above, use the following PHP scripts.

  • Netbeans has a PHP profiling capability.

    27. Coding standards

    After you get comfortable with PHP, you can move on to learning coding standards. There are differences between standards (Zend , Pear), choose your own and stick to it always.

    28. Keep functions out of loops

    You kill performance when you put functions in a loop. The longer the cycle, the more execution time you get. If you want to reduce execution time, take functions out of loops.

    Note: Using this logic, try to take as many operations out of the loop as possible. Consider whether you really need to create a variable every time you iterate through the loop. Do I need to call the function every time? Of course not:)

    29. Don't breed variables

    Some people copy the values ​​of predefined variables into variables with short names to make their code clearer. This leads to redundancy and potentially doubles the memory footprint of your script. Here are examples of bad and good use of variables:

    $description = strip_tags($_POST["description"]); echo $description;

    echo strip_tags($_POST["description"]);

    Note: Speaking of doubling the memory consumption is actually a misconception. PHP implements memory management based on a copy-on-write approach. This means that you can assign the same value to multiple variables and don't worry about the data being duplicated in memory. It can be argued that a "good" example is a good example of good code, but it certainly isn't faster.

    30. Update to the latest PHP version

    While this seems reasonable, many people don't upgrade PHP when they should. PHP 5 is more performant than PHP 4. Check your server and make sure you have the latest version.

    31. Reduce the number of queries in the database

    The fewer queries to the database, the greater the performance of the PHP script. Utilities such as Stace (Unix) and Process Explorer (Windows) will help you find redundant processes and eliminate them.

    32. Don't be afraid to ask

    Only people try to hide the fact of their ignorance in a certain area. Nobody wants to look stupid! But how can we learn without asking? Feel free to use the forums and IRC StackOverflow, ask experienced PHP developers. The PHP site has a page

Bootstrap Framework: Fast Responsive Layout

A step-by-step video course on the basics of responsive layout in the Bootstrap framework.

Learn to typeset simply, quickly and efficiently, using a powerful and practical tool.

Make up to order and get money.

Free course "Website on WordPress"

Do you want to master WordPress CMS?

Get lessons on website design and layout on WordPress.

Learn to work with themes and slice the layout.

Free video course on drawing website design, its layout and installation on CMS WordPress!

*Mouseover to pause scrolling.

Back forward

Fundamentals of PHP Basics: An Overview for Beginners

PHP has been consistently on the list of the most popular programming and web development languages ​​for many years. Of course, there are other languages, but the ubiquity of sites based on the WordPress engine has in many ways served as an additional impetus to the even greater growth in the popularity of this language.

What is PHP?

PHP stands for Hypertext PreProcessor(something like "HTML preprocessor").

What does this mean? Let's start a little afar: there are two types of languages. One type is called "client", and the other - "server".

It means that client languages ​​work in the browser of each individual person. A typical representative of client languages ​​is JavaScript, which you have probably heard about and the result of which you have seen more than once.

If you want to learn more about JavaScript, check out this article.

All actions and commands that we set, say, in JavaScript, are performed by the browser, which means that the same code written by us is processed in one case by Internet Explorer, in another by Firefox, in the third by Opera, in fourth - Google Chrome, i.e. the browser that each individual person uses to view our page.

The browser thus has an alternative name - customer.

In case of server languages(which includes PHP) we see a different picture.

Our site is always located on some server, i.e. a powerful computer specifically designed to host many people's websites.

All commands and scripts written in PHP are executed on the server, and nothing else. After the PHP script is executed on the server, the server "gives" the result of its work, which we see in the browser.

It is important to understand the following point here: according to the source code of the web page, which can be viewed in any browser through an option like "Page source code" it cannot be determined whether PHP was used to create a given page or not.

It is impossible to do this precisely because PHP scripts are processed on the server, and a ready-made, processed version is transmitted to the browser. Basically just HTML code.

The difference compared to regular static HTML pages is one additional code processing step.

In the case of an HTML page, there is only one step: the browser processes the HTML code, i.e. page markup in accordance with certain rules, as a result of which we see the web page in its normal form.

In the case of a PHP page, there are two steps: first so-called PHP interpreter(handler) executes the PHP code (as a result of this, a simple HTML code is obtained), and after that the browser processes the result of this processing, i.e., in fact, the same stage is performed, which is the only one in the case of HTML- page.

In general, PHP works great in tandem with HTML. Moreover, you can insert PHP code into HTML code, and use PHP to display HTML markup. It's important to remember this simple point: No matter how complex your PHP code is, it will eventually end up as plain HTML.

Why use PHP?

HTML is 100% static. By embedding PHP code in our pages, we can ensure that the content of the same page was different depending on certain conditions(dynamic pages). Over the years of its existence, the PHP language has proven to be a great solution for creating dynamic websites.

Is PHP similar to other languages?

Yes. PHP is similar to ASP.NET, Perl, JavaScript, C#. You may not know any of them now, but learning PHP will allow you to master other languages ​​with more confidence in the future.

What do you need to get started?

To fully work with PHP on your computer, you need the following things:

1. Apache web server (it is used in most cases);
2. Database Management System (DBMS) MySQL (the content of the site is stored in the database);
3. Installed PHP interpreter;
4. Text editor in which you will write code;
5. Browser.

Now a little more about the first three points.

1. Web server is designed to imitate on your computer the same server, which will then host your site already hosted on the Internet. This is necessary so that you can write any PHP scripts on your computer and see how they work, make changes and edits to them. In a word, it is necessary for the so-called debugging.

2. MySQL DBMS needed to store information that will be on your site. In the case of HTML pages, all of the site's content resides directly within them. Each page contains a certain amount of information (content).

When using PHP, a database is usually used to store the useful content of a site. In the vast majority of cases, this is MySQL.

3. PHP interpreter is a kind of program that processes PHP code on a web server. Without it, we will not be able to execute our PHP scripts and see the result of their work.

How to install all these components on a computer?

There is a good solution that greatly simplifies this process and does not require you to have any knowledge in the field of setting up a web server, MySQL and PHP interpreter.

This is a special set. Denver, which already includes all three components. It is installed on a computer as a regular program and is ready to work without any preliminary settings.

Denwer is an ideal solution in the vast majority of cases, and for beginners it will be a lifesaver, as it allows you to start developing sites in PHP without having to learn a bunch of additional information on setting up a web server, MySQL DBMS and PHP interpreter.

Basics

To tell the server to process PHP code, you must use the following syntax when adding PHP to an HTML document:

The opening of a block of PHP code is denoted as ", and the closure is "?>" . Now let's change our code like this:

Please note that in this example we wrote everything in one line. Spaces and newlines do not play a role here and will not affect the final result.

In the example, we give the server the command echo(command for displaying information on the screen) and indicate that we want to display the phrase This is PHP in action. Each command in PHP is separated from the previous one by a semicolon at the end of that command.

PHP is more strict with respect to syntax and will not forgive you for missing semicolons, brackets, quotes, etc., as it could be the case with HTML. PHP in this case will report a syntax error that needs to be corrected and indicate the line where this error was made.

By the way, in this case, we might not have used a semicolon at the end of the command, since in this case it is the only one (command). However, it's best to always stick to good practices when working with code.

Declaring Variables

Variable in PHP is a kind of container that can contain certain information. In order to create such a "container", we need to name it and specify what should "lie" in it. This is done with the sign "$" , which means that we are dealing with a variable. Let's put it in a variable named test phrase This is PHP in action.

The result of processing this code will be exactly the same as in the previous example. The screen will simply display the phrase This is PHP in action. However, before that we directly output this phrase, and now we have entered this phrase into a variable test, after which they gave the command to display the value of the variable on the screen test.

How can we add some more text or other information to display on the screen?

Let's look at this with the following example:

As you can see, after the output of the variable test there is a space, then a period, then a space again. After that, quotes are opened, first there is one space, and then a sentence My name is Dmitry Naumenko., after which the quotes are closed.

Let's go through the steps and see what and what is needed here.

After outputting the variable test we kind of "add" additional text to the already existing output. This is done using the dot symbol. (.) .

The dot symbol means addition in PHP, but not the addition of numbers, but the addition of textual information, like the one with which we are working. After the dot, we indicate in quotes what exactly we want to add to the output, and write a new sentence.

Note that there is a space after the opening quotes. When displayed on the screen, it will be saved, so that our phrases will not merge. Those. we will get you output:
This is PHP in action. My name is Dmitry Naumenko.

If you remove that space, you get:
This is PHP in action. My name is Dmitry Naumenko.

I also want to draw your attention to the spaces on both sides of the point that produces the addition. These spaces do not play any role and are used only for clarity and convenience of perception. The following code will give us exactly the same result:

Therefore, write in the way that is more convenient for you in this case.

Inserting comments in code

First question - "What are they for?"

Comments are needed so that you can make notes, notes, explanations, etc. in your or someone else's code. while working on the code. Now it seems to you that everything is clear and obvious. As long as you remember perfectly why this variable is needed and what that function does.

Not much time will pass and without comments you will hardly be able to understand even your own code, not to mention other people's scripts. Therefore, the competent use of comments is an urgent need.

PHP usually uses two types of comments:

Of course, comments only work within blocks of PHP code. And ?> .

Rendering HTML with PHP

As I mentioned earlier, PHP and HTML work great together. Just because we're inside a block of PHP code doesn't mean we can't display text in a paragraph or in bold.

This is the text in bold."; ?>

As you may have guessed, the result of this code will be the output to the browser of this line in bold.

Creating the first function

First of all, a few words about what a function is.

Function- this is a kind of mini-program that performs some useful work and gives us the result.

It makes sense to use functions in those cases when you need to perform the same type, template actions. In this case, we write such a mini-program, which significantly reduces the amount of code and, accordingly, our efforts.

The syntax for creating a function is as follows:

Let's say if we want to write a function that calculates the sum of the numbers 10 and 5, we can do this:

We create a function named sum and in its body we indicate that it should display the sum of the numbers 10 and 5. After that, we call the function sum. Calling a function essentially means executing it.

In this example, we are not using any arguments (see function syntax above). What are arguments and what they are for, we will consider directly with an example. We modify the code that we have, making it more flexible and functional:

Now when creating a function sum we specify two arguments separated by commas in brackets - $slagaemoe1 And $slagaemoe2. In the body of the function, we add and display not specific numbers, but the values ​​of variables $slagaemoe1 And $slagaemoe2(i.e. these same arguments).

Now we just need to call the function, while passing it in brackets the two arguments that it "expects". We specify the numbers 10 and 5, resulting in 15. Passing the function sum other numbers we will, of course, get a different answer.

I hope this overview has helped you understand what PHP is and what it is for, what advantages it has over static HTML, and how you can use some of its simplest features.

Dmitry Naumenko.

P.S. Do you want to move further in learning PHP? Check out premium tutorials on various aspects of website building, including PHP programming, as well as a free course on building your own CMS system in PHP from scratch. All this will help you master this powerful web development language faster and easier:

Liked the material and want to thank?
Just share with your friends and colleagues!


PHP programming language - Training course - Savelyeva N.V. - 2006.

PHP is currently one of the most popular languages ​​for implementing web applications. This course focuses on learning its basics. The emphasis is on the practical application of acquired skills.
The PHP language was created to solve a specific practical problem in the Internet environment (which one can be found out after reading the first lecture of the course). We will also try not to be distracted too much by theoretical considerations, and we will strive to solve a specific problem in each of the lectures. Most of the examples are taken from a real-life system: the virtual museum of the history of computer science. The first part of the course is devoted to learning the basics of syntax and control structures. After that, client-server technology is considered as the main area of ​​application of the PHP language. Then we turn to the study of the most useful built-in functions in our opinion and solving practical problems with their help. Although the object model in PHP is not the richest, its fundamental presence allows you to describe object data models in a natural way. As a basic model, the model of the document of the virtual museum of informatics will be considered. After that, a number of applied aspects will be considered: working with the file system, with the database, strings, sessions, DOM XML - all this will allow us to consider the key tasks of the practical use of the language.

PHP, MySQL for Beginners - Andy Harris - 2005.

This book will help you learn how to program in PHP and create databases in MySQL. If your goal is to write programs for web servers, then this book is for you. You will learn all the basic concepts of programming languages, in particular, learn the commands and syntax of the PHP language. You will also learn how data is used in modern environments, in addition to all this, you will also learn the programming process itself.


Download and Read PHP, MySQL for Beginners - Andy Harris

PHP - Learning by Example - Kukharchik A.

PHP - Learning by example - Kukharchik A. - 2004.

The basics of PHP, a popular scripting language for Web pages, are presented in a simple and accessible way. Performing simple examples, the reader will be able to master the basics of PHP programming, create a dynamic page, a site visit counter, a voting system, an address book, an online store. Typical errors in the use of scripts are described, as well as ways to correct them. The book contains code snippets that you can use to create your own projects.

It is intended primarily for beginners, but it can also be useful for experienced programmers using PHP.







2022 gtavrl.ru.