Results 1 to 15 of 15

Thread: PhP & MYSQL the Tutorial

  1. #1
    the roXor <3 Arbalest's Avatar
    Join Date
    Jan 2008
    Location
    above
    Age
    37
    Posts
    1,015

    PhP & MYSQL the Tutorial






    Between blogs, social networks, customizable homepages.In the recent years, Web sites gained in
    features and at the same time it became more and more complex.

    That time of the "personal web page" is far! There a time when we could simply create a basic site
    A bit of text, some pictures: wp here is Our personal site was ready.
    Today it is different: it must move! We expected that a site is regularly updated:
    we want to see news on the homepage, we wants to comment, discuss on forums,
    Briefly, participate in the life of the site.

    The PHP language has been designed precisely to create sites "live" (known as dynamic sites). If
    you want you also learn to create websites dynamic, it's your lucky day: you're on
    a course for beginners in PHP!
    The key is to read the entire chapters in order. Then it goes all alone and you
    soon wonder what you are capable of doing!

    To use PHP, you must know in advance XHTML and CSS.
    What do you mean these languages do you say anything?
    You do not even know what a "language"?
    It is therefore necessary that you first read my class website design in [URL="http://eurobattle.net/showthread.php?t=101610"]XHTML and CSS[/URL] before coming back here!

    what makes the success of the Web today, is both its simplicity and ease of access. An ordinary web surfers did not need to know "how it works behind". And fortunately for him.

    if you read my tutoriel of (x)html & css then Congratulations you are officielly an apprentice webmaster but it still not over , above all, you gonna need to know the basics of running a website.
    What is a server and a client?
    How does one's dynamic site?
    What does PHP and MySQL?

    This first chapter is here to answer all these questions and show you that you are able to learn to create dynamic websites.
    All readers will be reassured to know in the end they start at the same level!

    How does the web Work

    When you want to visit a website, you type its address in your web browser, either Firefox, Internet Explorer, Opera, Safari or another.
    But do you ever wondered how did the web page to reach you?

    You should know that the Internet is a network of computers. These can be classified into two categories:
    • Customers: These are Internet computers as you. Your computer is therefore part of the class of customers. Each client represents a visitor to a website. In schemes that follow, the computer of a client will be represented by this image:
    • The servers : they are powerful computers that store and deliver web sites to users, that is to say to customers. Most Internet users have never seen a server of their lives. However, the servers are essential for the proper functioning of the web.

    Note:Most of the time, the server has no screen: it stays on and works alone without human intervention, 24/24, 7 / 7. A true convict labor xD .

    We summarize: your computer is called the client, while the computer that owns the website is called the server. How do the two communicate?

    It is precisely here that makes the difference between a static and a dynamic site. Let's see together what is changing.

    Case of a static site

    When the site is static, the pattern is very simple, This happens in two stages:
    • The client asks the server to see a web page.
    • The server responds by sending the requested page.

    the communication is pretty basic:
    • "Hello, I am the client, I would like to see this web page."
    • "well sure, here's the page you requested me."


    On a static site,nothing else happens. The server stores web pages and sends them to customers who request them without change.

    For a dynamic site

    When the site is dynamic, there is an intermediate step: the page is generated.

    The client asks the server to see a web page.
    The server prepares page specifically for the customer.
    The server sends the page it has generated.


    The web page is generated whenever a customer demands it. This is precisely what makes dynamic sites live: the contents of a page can change from one moment to another.
    That is how some sites are able to show by example your nickname on all pages. Because the server generates a page each time he requests one, it can be customized to the tastes and preferences of the visitor (and display its nickname among others).


    When creating a website, one has to handle not one but several languages. As a webmaster, it is imperative to know them.

    Note :Some programs, called WYSIWYG (What You See Is What You Get), can help the novice to create a static web site without knowing programming languages behind ... But to achieve a dynamic site as we wish, u gonna to surpass that.

    • For a static site: XHTML and CSS


      Many languages have been created to produce websites. Two of them are an essential basis for all webmasters:

      XHTML is the language on the basis of websites. It's very similar to HTML but imposes few rules a bit stricter. Whenever possible I recommend using XHTML rather than HTML because it forces you to treat the source code of your site.
    • For a dynamic site: add PHP and MySQL


      Whatever the website that we want to create XHTML and CSS are essential. However, they are not sufficient to make dynamic sites. It must be supplemented with other languages.

      It is precisely the whole purpose of this course you will learn to manipulate PHP and MySQL to create a dynamic Web site.
      • PHP: it is a language that only servers understand and can make your site dynamic. This is PHP "generates" the web page as we saw on a previous schemes.
        This is the first language we discover in this course. It can work alone, but it really does interest if it is combined with a tool such as MySQL. Here is a PHP code:
        <?php echo "you are the visitor n°" . $nbre_visitors; ?>
      • MySQL: this is called a DBMS (Database System Management ). Simply put, its role is to record data in an organized manner to help you find them easily later. Thanks to MySQL that you can save the list of members of your site, posts on the forum, etc.. The language that communicates with the database is called SQL. Here is a code in SQL:
        SELECT id, author, message, datemsg FROM goldbook ORDER BY datemsg DESC LIMIT 0, 10


    Note: PHP and MySQL are called free software. Among other things, it gives you guarantees of sustainability: everyone can contribute to their development, you may not see all webmasters ignore the PHP and MySQL overnight, and it is very important !
    On the other hand, PHP and MySQL are available for free. This means something important: you will not pay a cent to build your website
    .

    PHP can work by itself and sufficient to create a dynamic site, but things get really interesting when combined with a DBMS such as MySQL. However for simplicity, let us forget for the moment about MySQL and let's focus On PHP.

    PHP generates XHTML


    Customers are unable to understand the PHP code, they know that XHTML and CSS. Only the server can read PHP.

    PHP's role is precisely to generate XHTML (you can also generate the CSS, but it's rare), the code is then sent to the client in the same way as a static site:


    PHP has decided what will be posted on the web page sent to the visitor


    PHP is a programming language used on many servers to make decisions. It decides PHP XHTML code that will be generated and sent to the customer every time.

    To understand the appeal of all this, consider an example. Can be written in PHP: "If the visitor is a member of my site and is called Jonathan, Jonathan displays Welcome on the web. But if this is not a member of my site displays Welcome place and the visitor to register. "

    And the competition?

    XHTML and CSS have no competitors cause they are standards. Everyone is supposed to know how to use them on all websites.

    However, in terms of dynamic websites, PHP and MySQL are far from alone on the spot. I can not get a complete list of competitors, it would be too long (and boring!). However, for your general knowledge should at least know a few other big names.

    Firstly, if there is a tendency to combine PHP and MySQL to achieve powerful dynamic sites, do not mix the two. The former has different competitors in the second
    It is a very basic example of dynamic site: whether you are a registered member or not, you will not see the same things and will perhaps not have access to all sections.

    Competitors PHP


    Among the competitors of PHP include:
    • ASP. NET developed by Microsoft, it operates. NET framework familiar to C # developers (a framework is a set of libraries that provide services to developers). This language can be interesting if you are used to develop in C #. NET and you do not want to be disoriented.
    • Ruby on Rails: very active, this framework can be used with the Ruby language and allows for dynamic sites quickly by following certain conventions.
    • Django: It is similar to Ruby on Rails, but it is used in Python.
    • Java and JSP (Java Server Pages): more commonly called "JEE", it is particularly used in the professional world. It requires a certain rigor. The establishment of a JEE project is traditionally a bit longer and heavier, but the system is popular with professionals and institutions (which is used on the website of French taxes, for example).


    Which one in the lot? Which is better?


    Given the purpose of this course, you expect me to respond instantly "PHP!". But no. In fact, everything depends on your programming skills. If you've ever used Java, you will quickly feel comfortable with JSP. If you know Python, Django seems entirely appropriate.

    As for PHP, it stands out from its competitors by a large community that can help you quickly on the internet if you have any problems. The language is easy to use, ideal for beginners and professionals alike: Wikipedia and Facebook are examples of famous and popular sites that work with PHP.

    In short, there is no better choice. I recommend the language for which you are most certain to have someone to help you. The PHP in this sense is often a very good choice.

    Competitors MySQL

    Regarding databases, the choice is again very broad.
    However, while PHP and its competitors are mostly free and open, this is not the case for most DBMS.

    Among the competitors of MySQL, I advise you to know (at least in name):

    • Oracle DBMS is the most famous, the most complete and most powerful. Unfortunately, it is paying (and expensive), what the reserve rather businesses who already use it heavily. However, there are free versions of Oracle including for those who want to learn to use it.
    • Microsoft SQL Server by Microsoft, it is often used in combination with ASP. NET, although it can be used with any other language. It is rewarding, but there are limited free versions.
    • PostgreSQL: it is a free and open DBMS such as MySQL, which offers more advanced features. Sometimes compared to Oracle, he remains a long way to go. It has a community a little less important as MySQL and Oracle.
    • SQLite: the DBMS the simplest and smallest. It is free but has very few features (which is sometimes enough). Its big advantage is to be very light.





    As you can see, you can choose between many tools to achieve a dynamic site. Most of them are free.

    Know that you can combine a priori these tools as you see fit. For example, you can easily use PHP with a database other than MySQL, as Oracle or PostgreSQL. Similarly, MySQL can be used with any other language: Java, Python, Ruby, etc..

    However, the combination "PHP + MySQL" is probably the most common. It is no coincidence that this tutorial deals with these two tools that have proven their values



    Again, this list is not exhaustive but presents at least a few big names.
    For information, MySQL DBMS is by far the most free and unrestricted use. Among the solutions professional pay, Oracle is the most advanced and most widely used but its use is mainly reserved for large companies.

    Ultimately, if your means are limited, you do not have much choice for the DBMS. MySQL is the most appropriate because it is free,powerful and used by many people .

    You should now have a good idea about PHP and MySQL. If you remember that
    PHP generates XHTML personalized for each visitor and MySQL is used to store data, you already know the principal.

    In the first part of this course we will learn PHP smoothly. We therefore put aside
    MySQL will not storing data in a first time. Once you have acquired a certain
    level in PHP, that's it for today see you all in the 2nd lesson for both windows and ubuntu
    Last edited by Arbalest; 31st August 2010 at 12:01 AM.

  2. #2
    Safelist Member ss-darky's Avatar
    Join Date
    Oct 2008
    Location
    Cluj Napoca, Romania
    Age
    35
    Posts
    825
    i must disagree on which is better. imo asp.net with c# is the absolute best as learning wise and security. and ofc it's pure oop while php uses "fake" oop tactics.

    on another note: this is a very fine guide! congrats on it! keep up the good work


    Hidden Text click here to show

  3. #3
    the roXor <3 Arbalest's Avatar
    Join Date
    Jan 2008
    Location
    above
    Age
    37
    Posts
    1,015
    You now know that PHP is running on the server and that its role is to generate web pages. But
    Only one server can read the PHP on your computer is not a server. How the hell are you able
    create a dynamic website if PHP does not work in you?

    Not to worry: we will temporarily turn your computer into a server for you
    can run PHP and work on your site dynamics. You're ready to program after
    read this chapter!

    so What kind of programs do we have need ?

    Depending on whether it creates a static or dynamic site, you need different software.
    In fact, make a dynamic site requires unfortunately for us a little more software!

    case of static site
    Webmasters who create static sites with XHTML and CSS are lucky, they have usually already have all the programs they need:

    • A text editor: in theory a program such as Notepad shipped with Windows only, although it is recommended to use a bit more advanced tool like Notepad + +. We will discuss the choice of the publisher at the end of this chapter.
    • A web browser: it allows to test the web page. You can use such as Mozilla Firefox, Internet Explorer, Google Chrome, Opera, Safari, or any other browser you are accustomed to go on the web. It is advisable to regularly test your site on different browsers.

    However, for those of us who work on dynamic sites, these tools are not enough. It is necessary to install additional programs

    case of dynamic site
    For your computer to read the PHP, it must behave as a server. Do not worry, you do not need to buy a special machine for that: it is enough simply to install the same programs as those found on the servers that deliver Web sites for users.

    These programs that we will need, what are they?

    • Apache: this is called a web server. It is the most important of all programs, it is he who is responsible for delivering web pages to visitors. However, Apache only handles static websites (it can handle only HTML pages). It must therefore be complemented with other programs.
    • PHP: it is a plug-in for Apache that makes it capable of handling dynamic web pages in PHP. Clearly, combining Apache and PHP, our computer will be able to read web pages in PHP.
    • MySQL: the software management database which I have mentioned in the introduction. It can record data in an organized manner (as the list of members of your site). We will not need immediately, but as the install immediately.


    All these elements that will help us to create our dynamic site are free and open. Certainly, there are other (sometimes paid), but the combination Apache PHP MySQL is the most common on web servers, so much so that created "packages" all loans that contain all these elements. It is possible to install one but it takes more time and you will gain nothing (unless you're a server administrator, which should not be your case).

    We'll see how to install the "pack" that fits according to your operating system later in this chapter.


    For Windows : Wamp


    There are several packages all ready for Windows. I suggest you use WAMP Server which has the advantage of being regularly updated and available in French.

    Start by downloading WAMP on its official website. Visit the "Download". You do not have to fill out the form, you just walk down to the bottom of the page and click on "Download WampServer.

    Once downloaded, install it by leaving all the default options. It should install to a directory like C:\wamp and create a shortcut in the Start menu.

    When you start WAMP, an icon should appear in the bottom right of the taskbar, next to the clock:


    If a window appears telling you that the firewall blocks Apache, click Unblock. You have no reason to worry, it's perfectly normal.
    By default, WAMP is in English ,You can now launch the WAMP homepage. Left click on the WAMP icon (note I said this time left click) and click on Localhost.

    A web page similar to the screenshot below should open in your favorite browser (Firefox for example). If the page is displayed in your home, this means that Apache is running.A web page similar to the screenshot below should open in your favorite browser (Firefox for example). If the page is displayed in your home, this means that Apache is running.


    Note : The web page you see on the screen was sent to you by your own Apache server that you installed along with WAMP. You're simulating the operation of a web server on your own machine. For now, you're the only surfer to access it. They say that works "locally". Note that the URL displayed in the browser address bar is http://localhost/or http://127.0.0.1/, which means that you are browsing a website located on your own computer .

    Return to the home page of WAMP and refresh the page (you can press the F5 key). The section "Your projects" should now display "tests" for WAMP has detected that you have created a new folder

    You create it thy first web pages in PHP.

    You can click on the link "tests". Since you have not yet created a PHP file, you should see a blank page like this:

    If you have the same result, this means that everything works. Congratulations, you installed WAMP and it works fine. You're ready to program in PHP!

    You can skip the following sections which relate only to users running Linux(ubuntu/kbuntu).

    Under Linux

    Under Linux, it is common to install Apache, PHP and MySQL separately. However, there are also packages all ready as XAMPP (Apache MySQL Perl PHP X), formerly known as LAMPP.

    This package is more comprehensive than for Windows WAMP or MAMP for Mac OS X. We will use only part of the installed elements.

    so this is a how-to for setting up a web development environment easily. This guide will install the XAMPP lampp stack into /opt, setup an easy way to start it up and shut it down, and link a folder in your home directory to the webserver.

    Two easy steps:

    • Download the most recent version of XAMPP: (at time of writing 1.5.3a)
      [url]http://prdownloads.sourceforge.net/x...ar.gz?download[/url]
      (Source URL: [url]http://www.apachefriends.org/en/xampp-linux.html#374[/url])
    • Extract the archive to /opt using sudo: (make sure you are in the directory that you downloaded the archive to)


    which means right after downloading packs move the pack in desktop => open terminal and type :

    cd ~/Desktop
    You must become root to install and run XAMPP.
    root is the account administrator of the machine that has the right to install such programs. Normally, just type su and enter the root password. Under Ubuntu, it will type sudo su and enter your usual password like this :
    sudo su
    You must now extract the compressed folder in / opt. To do this, just copy the following command:
    sudo tar xvfz xampp-linux-1.5.3a.tar.gz -C /opt
    and it's done
    now to start it up, open a terminal and type this:
    sudo /opt/lampp/lampp start
    and once u're done,you can stop it by opening a terminal and type this:
    sudo /opt/lampp/lampp stop
    in bonus for more Additional XAMPP commands open a terminal and type this:
    sudo /opt/lampp/lampp

    and for those who use the sweet gtk/python control panel again terminal and type :
    gedit ~/.local/share/applications/xampp-control-panel.desktop
    Paste the following into the open file , save and exit.
    [Desktop Entry]
    Comment=Start/Stop XAMPP
    Name=XAMPP Control Panel
    Exec=gksudo "python /opt/lampp/share/xampp-control-panel/xampp-control-panel.py"
    Icon[en_CA]=/usr/share/icons/Tango/scalable/devices/network-wired.svg
    Encoding=UTF-8
    Terminal=false
    Name[en_CA]=XAMPP Control Panel
    Comment[en_CA]=Start/Stop XAMPP
    Type=Application
    Icon=/usr/share/icons/Tango/scalable/devices/network-wired.svg
    "XAMPP Control Panel" will show up in your applications menu under Internet. Use the Alacarte Menu Editor to move it around.
    now just line windows open your brower which is in ubuntu by default firefox and go to: [url]http://localhost/[/url]
    Location of files and uploading

    XAMPP by default uses /opt/lampp/htdocs as the root web directory. The easiest way to start working on files is to link a folder in your home directory into this directory.
    My user name is arbalest so I have /home/arbalest/public_html linked to /opt/lampp/htdocs/arbalest. So if I navigate to [url]http://localhost/arbalest/[/url] I get a listing of all the files/folders in that directory. (As long is there isn't a index.php/html/etc file)
    To set this up, run in a terminal:

    • Make public_html directory in home directory:
      mkdir ~/public_html
    • Link to /opt/lampp/htdocs
      sudo ln -s ~/public_html /opt/lampp/htdocs/$USER

    where $USER is to be replaced by ur own like mine is arbalest
    Now any files and folders you place in ~/public_html will be published to your personal webserver.
    Bookmark [url]http://localhost/username[/url] to make this easy to access.
    as for the editor i already recommanded notepad++ for windows for ubuntu there is a bunch of them most known are vim , emacs and bluefish
    personally i use bluefish it's almost alike notepad++

    Whatever software you use, do not worry, it does not change at all how you learn PHP manipulation will be exactly the same for everyone.

    By now you should have installed a pack type WAMP or XAMPP to run the PHP and a text editor like Notepad + + or bluefish .

    From the next chapter we attack the code: we will start to discover PHP instructions. This means that you will do your first manipulations in the next lesson
    last note in case of images fail i've uploaded them down the post
    that's it for now see you in the next lesson
    Last edited by Arbalest; 8th September 2010 at 05:49 AM.

  4. #4
    the roXor <3 Arbalest's Avatar
    Join Date
    Jan 2008
    Location
    above
    Age
    37
    Posts
    1,015
    Quote Originally Posted by ss-darky View Post
    i must disagree on which is better. imo asp.net with c# is the absolute best as learning wise and security. and ofc it's pure oop while php uses "fake" oop tactics.
    agreed with that , the idea is not to influence the reader
    on another note: this is a very fine guide! congrats on it! keep up the good work
    thx :]

  5. #5
    the roXor <3 Arbalest's Avatar
    Join Date
    Jan 2008
    Location
    above
    Age
    37
    Posts
    1,015
    in the first chapter, we have discovered principle of operation of PHP. Here we
    move to the concrete and make our very first page PHP web.

    Do not expect an extraordinary result (in is the page we will create will not do anything special) but it will allow you to take our
    brands. You'll understand how particular separates the XHTML standard PHP code.

    Are you ready? Let's go!

    PhP Tags
    To use PHP, you will have to introduce a new tag ... and it is a bit special. It starts with <?Php and ends with [/color]?>[/color]. And the PHP code will be inside.

    here is the empty tag :
    <?php ?>
    Inside, we therefore write the PHP source code:
    <?php /* php code is written here */ ?>
    One a PHP can easily written over several lines. In fact, it is necessary mostly because the PHP will make several lines. This will give something like this :

    <?php
    /* php code is written here
    here
    and here too */
    ?>
    Note :There are other tags to use PHP, for example <? ?>, <% %>, Etc. ... Do not be surprised if you see some of them. However, <?Php ?> Is the most correct, that's why we'll continue using it along with this tutorial.

    Insert a PhP tag in the mid of XHTML code
    The PHP tag that we have discovered is inserted in the middle of XHTML as I have said earlier. To take the example we saw in the previous chapter:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
    <head>
    <title>testing php tags</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    </head>
    <body>
    <h2>test1</h2>

    <p>
    This Page contain xhtml code along with php tags.<br />
    <?php /* here insert php code */ ?>

    </p>

    <ul>
    <li style="color: blue;">text written in blue</li>
    <li style="color: red;">red text</li>
    <li style="color: green;">green</li>
    </ul>

    <?php
    /* some php
    even more php*/
    ?>
    </body>
    </html>
    Of course this page does not work because we have not yet written any real PHP code (they are just tags example). Everything you need to remember here is that when you want to put PHP code, presto, you open a PHP tag: <?Php ?>

    a question is be asked in here : You can put a PHP tag anywhere in the code?

    Yes Anywhere you want, not just in the body of the page by the way: you can put a PHP tag in the header of the page.
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
    <head>
    <title>testing php tags<?php /* PHP Code */ ?></title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    </head>
    or even like this :

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
    <head>
    <title>testing php tags</title>
    <meta http-equiv="Content-Type" <?php /* PHP Code */ ?> content="text/html; charset=iso-8859-1" />
    </head>
    How does it work? what it's for?
    Remember that PHP generated XHTML code, to better understand the how we'll start learning to display text in PHP.

    Displaying text
    Well that's all well and good, but it is time to start writing code php?
    Great news: now you learn your first statement in PHP.

    Well do not expect something extraordinary, your PC is not going to dance the samba itself.

    You will however understand a little better how PHP works, that is to say how it generates XHTML code. It is essential to understand this. :P

    The echo statement
    PHP is a programming language, which was not the case for XHTML (it talked rather description language because it can describe a web page). If you have programmed in other languages like C or Java, this should not surprise you. However, in this course, we start from zero so I'll assume that you have never done programming before.

    Any programming language contains so-called instructions. We wrote a line in general, and they all end in a semicolon. An instruction to command the computer to perform a specific action.

    Here, the first statement that we will discover the ability to insert text into the web page. It is the echo statement, the simplest and most basic of all the instructions you need to know.
    Here is an example of how to use this statement :


    <?php echo "this is some text"; ?>
    As you can see, inside the PHP tag is written followed by the echo statement to display text in quotation marks. The quotes can delimit the beginning and end of the text, it helps the computer to identify. Finally, the statement ends with a semicolon as I had predicted(rofl), which means the end of the investigation.

    Note: there is a identic statement called print, which does the same thing. However, echo is most commonly used.
    by the way can also request the display of tags. For example the following code works fine :

    <?php echo "this is some <strong>text</strong>"; ?>
    The word "text" will be displayed in bold with the presence of <strong> and </strong>

    [color=red]allright so How do i display quotes inside the quotes?[/quote]

    Good question. If you put a quotation mark, it means for the computer to display the text stops here. You might do better to plant your beautiful code and have a terrible "Parse error".

    The solution is to precede the quote with a backslash the \ like this :
    <?php echo "this is written using\"only\" PHP."; ?>
    You know that the PHP code is inserted in the middle of XHTML. So let's go take a basic page in XHTML and put ahead of PHP code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
    <head>
    <title>Notre première instruction : echo</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    </head>
    <body>
    <h2>displaying text by using php</h2>

    <p>
    this line is written with(x)HTML.<br />
    <?php echo "this one is with php."; ?>
    </p>
    </body>
    </html>
    I suggest you copy and paste this source code in your text editor and save the page. We'll try it and see what it produces as a result.

    But in fact, you remember how you should save your php page?
    Save the page with the extension .php, displaytext.php for example, in the tests Folder that I've been creating. It should be located in C:\wamp\www\tests under Windows.

    The key, regardless of your operating system, is that the file is saved in the www folder (or one of its subfolders) if the PHP file will not run!

    If you use Notepad ++,go language in menu then pick Pthen pick PHP short form of select file (php) into the window to save.
    now it's saved let's go take a look at it

    Testing a php page
    To test your PHP page, it depends on your operating system, but the movement is broadly the same.

    On Windows, start WAMP if not already done, then go to the menu=> Localhost, the homepage should opens. Here, if you've created the folder tests in the www directory as indicated in the previous chapter, you should see a link to the tests folder. Just click on it .

    A web page opens showing all the pages found in the tests folder. You should have the file displaytext.php. Click on: Your computer will then generate the PHP code and then open it. You have the results right before your eyes.

    The same result can be obtained by going directly to the address in your browser [url]http://localhost/tests/displaytext.php[/url] . The method should be virtually the same whether you're on Windows, Mac OS X or Linux,like this :

    [URL="http://tutoriliez.eb2a.com/test101.php"]test code[/URL]

    you're propably wondering wouldn't it be easier to just write that using (x)html?
    well i totally agree But you will soon see the value of this function. For the moment, since these are our first tests so don't expect much at start

    in the next lesson we're starting the migration (x)html to PHP we gonna start by transforming the last [URL="http://eurobattle.net/showpost.php?p=1101681&postcount=34"]tp made in html css[/URL] from (.html) to (.php) and we'll start learning how to use the php documention you can already check [url]www.php.net[/url] and we'll learn a new function the include(page.php)
    that's it for now you all in the next lesson
    Last edited by Arbalest; 24th September 2010 at 12:16 PM.

  6. #6
    the roXor <3 Arbalest's Avatar
    Join Date
    Jan 2008
    Location
    above
    Age
    37
    Posts
    1,015

    the "echo" statement and variables

    In the first chapter, we discovered the operating principle of PHP. Here we will
    concrete and move to realize our very first page PHP web.

    Do not expect extraordinary results (in is the page we will create will not do anything
    special) but it will allow you to take our brands. You'll especially understand how
    separates the XHTML standard PHP code.

    PHP tags :
    So you know that the source code of a page consists of XHTML tags (also known as tags). <ul> Example is a tag.

    The PHP code is inserted in the middle of XHTML. We will gradually put in our pages pieces of PHP code within XHTML. These bits of PHP code will be the dynamic parts of the page, that is to say the parts that can change by themselves (that is why we say they are dynamic).

    The form of a PHP tag :
    To use PHP, we'll have to introduce a new tag ... and it is a bit special. It starts with <?Php and ends with ?> like this :
    <?php ?>
    we'll therefore write the PHP source code within :
    <?php /* The PHP code goes here */ ?>
    One can easily write a PHP tag over several lines. In fact, it is necessary mostly because the PHP code will be multiple lines. This will give something like:
    <?php
    /* The PHP code goes here
    and here
    and here too */
    ?>
    Note:There are other tags to use PHP, for example <? ?>, <% %>], Etc. ... Do not be surprised if you see them. However, <?Php ?> Is the most correct, you learn so you use this tag more often.

    insert a PHP tag in the mid of XHTML :

    PHP tag that we just discovered fits in the middle of XHTML as I said earlier, here an example:


    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
    <head>
    <title>a test page for php tags</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    </head>
    <body>
    <h2>Test Page</h2>

    <p>
    This page contain php and xhtml tags<br />
    <?php /* the php code goes in here*/ ?>
    here few examples:
    </p>

    <ul>
    <li style="color: blue;">Text in Blue</li>
    <li style="color: red;">Text in Red</li>
    <li style="color: green;">Text In Green</li>
    </ul>

    <?php
    /* more php code
    again php */
    ?>
    </body>
    </html>
    [URL="http://tutoriliez.eb2a.com/example01.html"]test code [/URL]



    Of course this page doesn't show any php effect because we have not yet written any real PHP code (they are just tags for example). All you need to remember here is that when you want to put PHP code, hop, you open a PHP tag <?Php ?>
    you're probably wondering You can place a php tag anywhere in the code?

    Yes! Really anywhere. Not only in the body of the page from elsewhere: you can put a PHP tag in the header of the page, like this:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
    <head>
    <title>This is a test page <?php /*PHP Code*/ ?></title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    </head>
    Stronger yet, you can even insert a tag in the middle of a PHP tag XHTML : (the html code is getting owned xD)
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
    <head>
    <title>This is a test page</title>
    <meta http-equiv="Content-Type" <?php /*PHP CODE*/ ?> content="text/html; charset=iso-8859-1" />
    </head>

    Display text
    Well that's all well and good, but it is time to start writing code php?
    Great news: now you learn your first statement in PHP.

    Well do not expect something extraordinary, your PC is not going to dance the samba itself.

    However, you will understand a little better how PHP works, that is to say how it generates XHTML. It is essential to understand this, so be careful!
    The echo statement :
    Here the first statement that we will discover to insert text into the webpage. It is the echo statement, the simplest and most basic of all the instructions you need to know.

    Here is an example of using this statement:
    <?php echo "This is some text"; ?>
    As you can see, inside the PHP tag is written followed by the echo statement to display text in quotation marks. Quotes can delimit the beginning and end of the text, it helps the computer to locate. Finally, the statement ends with a semicolon as I had predicted, meaning the end of the trial.

    Note : there is an instruction identical to echo called print, which does the same thing. However, echo is more commonly used.
    You should know that we also have the right to request to display tags. For example the following code works:
    <?php echo "this is <strong>Text</strong>"; ?>
    The word "text" will be displayed in bold with the presence of <strong> and </strong>.
    let's say now you wanna display a quotation inside the text, it means for the computer to display text stops here. You may at best to crash your beautiful code and have a "Parse error"
    The solution consist to make a backslash \before and after the quotation mark like this :
    <?php echo "this text is written using\"Only\" in PHP."; ?>
    You know the PHP code is inserted in the middle of XHTML. So let's go, let's take a basic page in XHTML and place ourselves ahead of PHP code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
    <head>
    <title>our first test : echo</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    </head>
    <body>
    <h2>Displaying text with php</h2>

    <p>
    this line is written using only xhtml.<br />
    <?php echo "this one is \"Entirly\"written in php."; ?>
    </p>
    </body>
    </html>
    I suggest you copy and paste this source code in your text editor and save the page. We'll try it and see what it produces as a result.
    do you remember how you should save your PHP page?
    Registering a php page

    I explained how in the previous chapter but a little reminder can not hurt.

    Save the page with the extension .Php by picking "language" in the menu of notepad++ then pick "P" =>"php" save it as displaytext.php for example,in the tests Folder that I made you create. It must be located in C:\wamp\www\tests on Windows(for example).
    Once the page is saved,it's time to make a test .

    [URL="http://tutoriliez.eb2a.com/example1.php"]test code[/URL]

    and congratulations you just made your first php page wohoo

    PHP variables

    Displaying a specific text will work for you only in the beginning. For dynamically changing your website, you'll have to use php variables.

    Just like in math, you can calculate with actual numbers or with letters.
    2+2=4
    x+2=4
    x=2
    The same thing appears in php. To create a variable in php, you simpy write:
    <?php
    $<variable name>=<some value>;
    $number=3;
    ?>
    In this case, variable called $number will now hold the value of "3". You must always use $ sign in front of variable names.

    Naming Rules for Variables
    • A variable name must start with a letter or an underscore "_"
    • A variable name can only contain alpha-numeric characters and underscores (a-z, A-Z, 0-9, and _ )
    • A variable name should not contain spaces. If a variable name is more than one word, it should be separated with an underscore for example ($my_string), or with capitalization ($myString).
    There are several variable types. PHP automatically sets the type according to the value the variable holds.

    Basic variable types are:
    • Boolean : this variable type can only hold 2 values, TRUE or FALSE.
    • Integer : a full positive or negative number like 3, 999, -15 etc
    • Doublel : a floating point number, for example 3,6; 3,333333; -5,4; also 3,0!
    • String : a series of characters combined together, ex: cen, 4k.peace, trololol5567 etc. You can basically imagine it as a text of any kind.

    These 4 types will do for the start. Now let's test this out in a script. We will set few variables and check for their type with gettype() function.

    Put the php code in between the <body> tags.
    <?php
    $a=2;
    $b=2.0;
    $c=3.5467;
    $d="my name is cen"; //as you noticed, when declaring a string variable, we must use quotes!
    $e=TRUE;
    ?>
    What we've done above? We've set 5 variables called a, b, c, d and e and we gave them some value to hold. Now we can simply echothem.

    <?php
    $a=2;
    $b=2.0;
    $c=3.5467;
    $d="my name is cen"; //as you noticed, when declaring a string variable, we must use quotes!
    $e=TRUE;
    echo $a;
    echo $b;
    echo $c;
    echo $d;
    echo $e;
    ?>
    [URL="http://tutoriliez.eb2a.com/echo1.php"]test code[/URL]

    When you'll test this out on your server, you'll get a mess. All values will be displayed in one line, with no space between or anything. You would also want php to display each value in a new line. You would also maybe want to use only one echo to display all variables at once. To make this, we need to learn how to combine strings.

    Example: We want to combine 2 strings in one. To do this, we use a dot .


    <?php
    $name="Cen";
    $surname="Pro";
    $combined=$name.$surname;
    echo $combined;
    ?>
    [URL="http://tutoriliez.eb2a.com/echo2.php"]test code[/URL]

    If you test this out, you'll see that variables $name and $surname combined into one. Now when we know that, let's display our 5 variables above in a nicer form. Remember which xhtml tag sends you in new line? Yes, it's <br />.

    <?php
    $a=2;
    $b=2.0;
    $c=3.5467;
    $d="my name is cen"; //as you noticed, when declaring a string variable, we must use quotes!
    $e=TRUE;
    echo $a."<br />";
    echo $b."<br />";
    echo $c."<br />";
    echo $d."<br />";
    echo $e."<br />";
    ?>
    [URL="http://tutoriliez.eb2a.com/echo3.php"]test code[/URL]

    As you see, when we echo the $varsiables, we never use quotes on them, but whenever we add a string (some text) or html tags, we must use quotes( the " ").

    The dot between our variable and added html tag allows you to echo them together. Without the dot, we'de have to do it this way:

    <?php
    $a=2;
    $b=2.0;
    $c=3.5467;
    $d="my name is cen"; //as you noticed, when declaring a string variable, we must use quotes!
    $e=TRUE;
    echo $a;
    echo "<br />";
    echo $b;
    echo "<br />";
    .
    .
    ?>
    Which is not really comfortable. We can also use dot to echo everything in a single line.

    <?php
    $a=2;
    $b=2.0;
    $c=3.5467;
    $d="my name is cen"; //as you noticed, when declaring a string variable, we must use quotes!
    $e=TRUE;
    echo $a."<br />".$b."<br />".$c."<br />".$d."<br />".$e."<br />";
    ?>
    Result is the same.

    And now as I said, let's see what variable types do we have. To check this, we will use function gettype().

    <?php
    $a=2;
    $b=2.0;
    $c=3.5467;
    $d="my name is cen"; //as you noticed, when declaring a string variable, we must use quotes!
    $e=TRUE;
    echo "Variable a with value ".$a." is ".gettype($a)."<br />";
    echo "Variable b with value ".$b." is ".gettype($b)."<br />";
    echo "Variable c with value ".$c." is ".gettype($c)."<br />";
    echo "Variable d with value ".$d." is ".gettype($d)."<br />";
    echo "Variable e with value ".$e." is ".gettype($e)."<br />";
    ?>
    [URL="http://tutoriliez.eb2a.com/echo4.php"]test code[/URL]

    In the above script, we simply echoed some user friendly text, the value of a variable and it's type. Looking closely, you'll notice some interesting stuff about php.
    • php echoes 2 instead of 2.0 but the type is actually double
    • php transforms TRUE into 1. FALSE on the other hand equals 0.

    Understanding the above scripts, you should now know how to:
    • create variables and set them a value
    • echo variables
    • combine strings using . (dot)
    • echo differerent variable types alltogether using . (dot)
    • echo html code (in fact, you can display whole html code by echoing it with php!)
    • echo html code and quotes as an actual text on a website (below)
    • know that there are several variable types, each type serves a different purpose

    Addition to displaying quotes
    Arbalest above told you, that using \ in front of " will display the " and not treat " as a part of php code (it means a start or an end of the string). But let's suppose we want to display \" on the site. How would we do it? Putting another \ in front will leave you with a parse error.

    Also, let's say we want to display <br /> or some other html tag as an actual text on the website (maybe for tutorials etc) and not using it to go in next line. \<br /> won't work this time.

    In general, if you want to display a part of the code as a string, you use htmlentities() function.

    Let's display <br /> as a text on website without making it execute and going in new line.
    <?php
    echo htmlentities("<br />");
    ?>
    Results displayed is <br /> but not treated as a part of html code.

    This would be all for this time, if you have any questions, feel free to post them.



    Arbalest & cen
    Last edited by Arbalest; 25th October 2010 at 12:59 PM.

  7. #7
    the roXor <3 Arbalest's Avatar
    Join Date
    Jan 2008
    Location
    above
    Age
    37
    Posts
    1,015

    The Conditions & The loops

    Introduction


    welcome in a new chapter of php/mysql tutorial in this lesson we'll study the Conditions and Loops this lesson is quiet necessary to totally underdstand it, Indeed,
    you will very often obliged to use these 2 in your web pages.We'll first start with the Conditions.

    What are the conditions? Sometimes you need display different things depending on
    certain data. For example, if it's morning, you want to say "hello" to your visitors if it is
    evening he would be better to say "good night".

    This is where the conditions. They can give different orders according to PHP
    the case. For our example, we would say: If it morning show "Good morning." Otherwise, if it is evening,
    displays "Good evening". You will see, the conditions are really the foundation to make your website dynamicie to display different things
    according to the visitor, time of day, the date, etc.

    The basic structure: If ... Else

    A condition can be written in PHP in different forms. There is talk of conditional structures.
    The one I'll learn to use now is the basic of conditions. We will see more a little further.

    To study the structure If ... Else, we will follow the following plan:

    1. The symbols to know: it will first have to remember a few symbols that can make comparisons.
    2. the structure If ... Else: this is the big one. There you will see how a condition with If ... Else. Needless to say that it is essential to understand that.
    3. Multiple conditions: we just complicate our conditions. You'll see that we can indeed use multiple conditions at once.
    4. The trick bonus: because there is always a bonus to reward those who have properly followed .



    The symbols

    • == which mean "exactly equal"
    • > which mean "Higher"
    • < which mean "lower"
    • >= which mean "higher or equal"
    • <= which mean "lower or equal"
    • != which mean "different then"


    Note:There are two symbols "equal" == on the first line, and we must not confuse this with the simple = you've learned in the chapter on variables.


    Here's what to put in order to use condition:
    • To introduce a condition, we use "if"
    • then we add parentheses after the condition itself (you'll see that you can invent an infinite number of conditions).
    • Finally, we open braces within which instructions will be executed if the condition
      is satisfied.

    Since an example is always better than a long Speech here an example :
    <?php
    $age = 8;

    if ($age <= 12)
    {
    echo "hi boy !";
    }
    ?>
    Here, we ask PHP if the variable $ age is less than or equal to 12, displays "Hi boy!"

    You will notice that in almost all cases it is a variable that is provided.
    In our example, we work on the variable $ age. What matters here is that there are two possibilities: either the condition is met (age is less than or equal to 12 years) and then you see something, otherwise, well you jump instructions between curly brackets, nothing is done.

    Well we can still improve our example. We will post another message if the age is above 12 years:

    <?php
    $age = 8;

    if ($age <= 12) // here the age is bellow 12
    {
    echo "hello boy<br />";
    $autorisation_enter = "yes";
    }
    else // otherwise
    {
    echo "this place is for kids.. !<br />";
    $autorisation_enter = "No";
    }

    echo "Do you have permission to enter? The answer is : $autorisation_enter";
    ?>
    [URL="http://tutoriliez.eb2a.com/echo10.php"]test code[/URL]


    Well how this code works? First, I put multiple statements in braces (do not forget that you can put multiple statements).
    Then you noticed that I added the word else, which means "otherwise". Clearly, we ask: If age is less than or equal to 12 years, do this, otherwise do that.

    Try this snippet you, have fun changing the value of $ age (on the first line). You will see the message that appears changes depending on the age you specify!

    Of course, you put the commands you want braces. Here for example I posted a message, and I gave a different value to the variable $ autorisation_entrer, which might serve us later. For example:

    <?php
    if ($autorisation_enter == "Yes") // IF you have the authority to enter
    {
    // instructions to be executed when one is allowed to enter
    }
    elseif ($autorisation_enter == "No") // ELSE IF we did not have permission to enter
    {
    // instructions to be executed when one is not allowed to enter
    }
    else // otherwise (Variable contains neither Yes nor No, we can not act)
    {
    echo "Uh, I do not know your age, you can remind me please?";
    }
    ?>
    Multiple conditions

    Will we try to do is to give several conditions at once. For this, we will need new keywords. The key to know are :


    • && which mean => AND written by pressing the button 1 right above the "a" in keyboard
    • || which mean => OR written by pressing ALT Gr + 6 in keyboard
    here an example :
    <?php
    if ($age <= 12 && $sexe == "boy")
    {
    echo "hello kid !";
    }
    elseif ($age <= 12 && $sexe == "girl")
    {
    echo "we don't have barbies in here !";
    }
    elseif ($age >= 20 && $sexe == "girl")
    {
    echo "hello sugar !";
    }
    elseif ($age >= 20 && $sexe == "boy")
    {
    echo "Yo dude !";
    }
    ?>
    A small hint

    With the conditions, there is a trick to know.
    Know that the two codes below give exactly the same result:

    <?php
    if ($variable == 23)
    {
    echo '<strong>Congratulations !</strong> you found the number !';
    }
    ?>
    and

    <?php
    if ($variable == 23)
    {
    ?>
    <strong>Congratulations !</strong> you found the number !
    <?php
    }
    ?>
    As you can see, in the second column was not used to echo. In fact, you just open the brace ({), then close the tag php (?>), and you can put any text you want to display in HTML!
    Roughly handy when there are large amounts of text to display, and also to avoid having to take the lead with the backslashes before the quotes ("or ').
    However, you will think the accolade after close (inside a PHP tag of course).

    And after that, my faith, there is nothing particular to say. You will meet the conditions in almost all of the examples I give you later.
    You should not normally have problems to use conditions, there is nothing very difficult. Stick to restart the schedule I gave you the structure If ... Else, and apply to your case. We will also soon have the opportunity to practice a little, and you will see that the conditions are often required.

    A practical alternative: Switch

    In theory, the structures based on if ... elseif ... else that I just showed you enough to treat any condition.

    But then why complicate things with another structure?


    To promote the value of a switch, I'll give you an example a little heavy, with if and elseif as you just learned:

    <?php
    if ($note == 0)
    {
    echo "ouch thats an epic fail !!!";
    }

    elseif ($note == 5)
    {
    echo "this note sux man";
    }

    elseif ($note == 9)
    {
    echo "Close 1 try harder next time";
    }

    elseif ($note == 10)
    {
    echo "gg u evoided the fail";
    }

    elseif ($note == 12)
    {
    echo "not bad keep up ";
    }

    elseif ($note == 16)
    {
    echo "gg wp u're doing well !";
    }

    elseif ($note == 20)
    {
    echo "GG wp you rox !";
    }

    else
    {
    echo "Sorry, I don't have a message to display for this note";
    }
    ?>
    As you see, it is heavy, lengthy and repetitive. In this case, we can use another more flexible structure: it's the switch.

    The same example with switch (the result is the same, but the code is lighter):

    <?php
    $note = 10;

    switch ($note) // on indique sur quelle variable on travaille
    {
    case 0: // when $note = 0
    echo "ouch thats an epic fail !!!";
    break;

    case 5: // when $note = 5
    echo "this note sux man";
    break;

    case 9: // when $note = 9
    echo "Close 1 try harder next time";
    break;

    case 10: // when $note = 10
    echo "gg u evoided the fail";
    break;

    case 12: // etc etc
    echo "not bad keep up ";
    break;

    case 16:
    echo "gg wp u're doing well !";
    break;

    case 20:
    echo "GG wp you rox !";
    break;

    default:
    echo "Sorry, I don't have a message to display for this note";

    }
    ?>
    [URL="http://tutoriliez.eb2a.com/echo11.php"]test code[/URL]


    So test this code!
    Try changing the note (in the first trial) to see how PHP reacts! And if you want to make some changes to the code go ahead and make some tests!

    let's try to eexplain this :
    Firstly, there is much less braces (they mark only the beginning and end of the switch).

    box means "if." In the switch, it says early on which variable we work ($ note here). It tells PHP: I will analyze the value of $ note. Following are used to analyze each case box (box 0, box 10, etc..). This means: If the value is 0 ... Where the value is 10 ...

    Advantage: we no longer need to put the double equal! Default: it does not work with other symbols (<> <=> = =). Clearly, the switch can not test that equality.

    The default keyword at the end is the equivalent of a little else. That is the message that appears by default regardless of the value of the variable.

    There is one important thing to know: Suppose in our example that the note is 10. PHP will read: case 0? No. I jump. box 5? Either. I jump. box 7? Either. I jump. Box 10? Yes, I execute the instructions. But unlike elseif, PHP does not stop there and continued to read the instructions in box below! Box 12, Box 16 ... etc.

    To prevent this, use the break statement;. The break statement asks PHP to exit the switch. Once PHP falls on break, he released braces so he does not read the box below. In practice, we use very often break because otherwise PHP reads instructions below, which are not suitable.
    Try to remove the break in the preceding code, you'll understand why they are indispensable!

    When should I choose if, and when should I choose switch?


    It is mainly a problem of presentation and clarity. For a short and simple condition, we use the if, and when we have a series of conditions to analyze, we prefer to use switch to make the code clearer.

    The ternary : condensed conditions

    There is another form of condition, much less frequent, but I present to you anyway because you might one day fall on either. These so-called ternary.

    A triple is a condensed condition which does two things on one line:
    It tests the value of a variable in a condition.
    It assigns a value to a variable depending on whether the condition is true or not.


    Consider this example based on if ... else who makes a major $ boolean true or false depending on the age of the visitor:

    <?php
    $age = 24;

    if ($age >= 18)
    {
    $major = true;
    }
    else
    {
    $major = false;
    }
    ?>
    You can do the same thing in a single line through a ternary structure:


    <?php
    $age = 24;

    $major = ($age >= 18) ? true : false;
    ?>
    Here, all our previous test was done on one line!

    The condition tested is $ age> = 18. If true, then the value after the question mark (true here) will be assigned to the variable $ key. Otherwise, the value that follows the symbol "two points" to be assigned to $ key.

    It's a little twisted but it works.
    If you do not use this type of condition in your webpage, I understand very well. I must admit that the ternary are somewhat difficult to read because they are very condensed. But know how to recognize and understand if you encounter one day while reading the source code from someone else.
    Last edited by Arbalest; 14th November 2010 at 02:55 PM.

  8. #8
    the roXor <3 Arbalest's Avatar
    Join Date
    Jan 2008
    Location
    above
    Age
    37
    Posts
    1,015

    Part II the Loops

    within the series of basic knowledge of PHP I present you the loops.
    they gonna ask the computer to repeat instructions, soif you wonder what's a loop your're in the right place
    A simple loop: While

    What is a loop? It is a structure that operates on the same principle that conditions (if. else ..). Besides, you'll see that there are many similarities with the chapter on the conditions.
    Specifically, a loop to repeat instructions several times. Clearly, it saves time, it's very useful and often indispensable.


    • This is what happens in a loop:
    • As usual, the instructions are first executed in order from top to bottom (red arrow)
    • At the end of instructions, return to the first (green arrow)
    • And we start to read the instructions in order (red arrow)
    • And we return to the first (green arrow)
      etc etc ...


    The only hitch in this scheme is that it never stops! The instructions would be replayed endlessly!
    That is why, whatever the type of loop (while or for), indicate a condition. While the condition is fulfilled, the instructions are replayed. Once the condition is not fulfilled, it finally comes out of the loop (gg wp!).

    Here's how with a simple loop: while
    <?php
    while ($loop_condition == true)
    {
    // Instructions to execute within the loop
    }
    ?>
    what happened in here is that we said in PHP : AS Long as $loop_condtition is true, execute the instructions bellow :

    The instructions are repeated in a loop located between the braces {and}. Anyway there I tell you nothing, you start to get used to seeing braces everywhere.

    This is not much more complicated than that, there is little more to know. However, I'm going to show you one or two examples of using loops, so you can see what it can be used ...

    For our first example, we will assume that you have been punished and that you must copy 100 times "I must not look at fly swatter when I learn PHP."
    Before you had to take his troubles patiently and it was taking heuuuures. Now with PHP, we'll do that in a blink of an eye! xexexe

    PHP Code :
    Hidden Text click here to show


    [URL="http://tutoriliez.eb2a.com/loops1.php"]test code[/URL]

    The loop includes the condition: AS long as$ number_of_lines is less than or equal to 100
    we'll do 2 things:
    • The echo, which displays the text in PHP. Note that there is an HTML tag <br /> at the end : it's not surprising it mean each sentence is written on a single line.
    • Then a strange instruction: $ number_of_lines++; (if your're asking woot iz that?) Look at my comment: this is exactly the same thing. In fact, it's a shorter way of adding 1 to the variable. This is called the increment (another noobish way to say that we'll add +1 the variable) )


    In here, the value of the variable increases: 1, 2, 3, 4 ... 98, 99 ... Once the variable has reached 100 and and it's about to go 101, the loop exits without displaying the echo. And now, we wrote 100 lines in the blink of an eye
    And if the punishment had been bigger, no problem! Just change the condition (eg put "as long as it is less than 500" to write it 500 times).

    Note : ALWAYS ensure that the condition will be furfilled at least once. If it is not, then the loop will run forever!
    PHP will not normally work more than fifteen seconds. He stops himself if he sees that his work takes too long and will display an error message
    .

    here another example for fun

    PHP Code:
    Hidden Text click here to show


    [URL="http://tutoriliez.eb2a.com/loops2.php"]test code[/URL]

    and this example is much like the previous one. The peculiarity here is that it displays every time the value of $ number_of_lines++ (it lets you see that its value increases gradually)

    A more complex loop : For

    for is another type of loop in a form slightly more condensed and more convenient to write. This forum frequently used in practice.

    However, note that for and while giving the same result and serve the same thing : repeat instructions in a loop. One may seem more suitable than another in some cases, this also depends on tastes(personally i rarely use the while).

    So how does the "for" work ? It closely similar to "while", but this is the first line that is a bit special. So you can see the difference with the while, I take exactly the example above, but this time with a for:

    PHP Code :
    <?php
    for $number_of_lines = 1; $number_of_lines <= 100; $number_of_lines++)
    {
    echo 'This is the Line n°' . $number_of_lines . '<br />';
    }
    ?>
    let's escribe each of these elements:
    • The first is used for initialization. It is the value that is given initially to the variable (here it is 1).
    • The second is the condition. As for the while, until the condition is furfilled, the loop is executed again. Once the condition is no longer furfilled, the loop stops.
    • The third is the increment, which allows you to add 1 to the variable each loop.


    The last two codes give exactly the same result. The place is the same as while, but together on one line all you need to know about the operation of the loop.

    How do I know which one to choose when I'm between a while and a for?
    • The while loop is simpler and more flexible, we can do all types of loop but you can forget to do certain steps, such as incrementing the variable.
    • On the other hand, is well suited for when you must count the number of times you repeat the instructions and it helps to remember to do the increment to increase the value of the variable!

    that's it for now see u on the next lesson : Functions

  9. #9
    the roXor <3 Arbalest's Avatar
    Join Date
    Jan 2008
    Location
    above
    Age
    37
    Posts
    1,015

    Functions

    Introduction
    In PHP, we don't like to repeat the same code several times.
    To address this problem, that's why loops execute instructions several times.
    Here we will discover another type of structure that do the same and which is important to know it's called:

    functions

    Such as loops, functions can prevent having to repeat the PHP code that is used often.
    But while the loops are all stupid machines xD barely able to repeat 200 times the same thing,
    functions are robots "smart" that fit depending on what you do and it's greatly automate most common tasks.

    What is a function?
    A function is a series of statements that performs actions and returns a value. In general, when you need to perform a little long you will need it again later, it is advisable to ascertain whether there is already a function that does this for you. And if the function does not exist, you can create it.
    Imagine that the functions are robots like this one :


    You do not know what is happening inside the robot, but you can press a button to ask him to do something specific. With functions, the same principle!

    Here's the kind of dialogue we can have a function:

    - You, the function calculCube, give me the volume of a cube whose edge is 4 cm.
    The function performs the required calculations and answered:
    - This cube has a volume of 64 cm3.

    We give input to the function a parameter on which it will do the calculations (here the edge length: 4) and the function returns us to output the result: 64.


    With the function, you do not need to remember how to calculate the volume of a cube. Well here it was pretty simple (it was enough to make 4 * 4 * 4), but you will often need to make operations more complex and functions you will not have to worry about the details of the calculations.
    also remember this : The information that is given as input to the function are called parameters (a word to to keep in mind).

    I chose a mathematical example here because I found it simple and speaking, but in practice it does not spend his time to calculate logarithms and exponentials when creating a website, I agree.

    functions do Specific jobs it can retrieve informations such as date and time, encrypt data, send emails, conduct searches in the text, and much more!

    PHP Functions

    in PHP we call the function to operate by using it's name like this :

    <?php
    calculCube();
    ?>
    Note: CalculCube function is an imaginary function, it won't work if u try it (unless you create it).
    If you want to send a parameter (either a number, string, boolean) it must be written in brackets:
    <?php
    calculCube(4);
    ?>
    this way thefunction calculCube will work with the number 4.

    Often, several functions accept several parameters. In this case you must separate them with commas:

    <?php
    fonctionImaginaire(17, 'green', true, 41.7);
    ?>
    and the function will use those 4 parameters, and to retrive the result you do it like this

    <?php
    $volume = calculCube(4);
    ?>
    Note: you can send several input parameters to a function as we have seen, but instead the function can return only one value in return. There is another way to get around this limitation by combining variables into a variable array which will be the subject of the next lesson.

    PHP Functions ready-to-use

    PHP has hundreds and hundreds of functions ready for use, you can take a look by visiting [URL="http://www.php.net/"]php official website[/URL]
    These functions are very practical and very numerous. In fact, this is partly what is the strength of PHP functions are really good because they cover almost all of your needs , if u can't 1 that suit you , you create your own
    let's take some examples :

    • strlen : This function returns the length of a string, that is to say the number of letters , number also it includes spaces
    • str_replace : str_replace replaces one string with another including just 1 letter
    • str_shuffle : this one mix randomly the characters from your string
    • strtolower : strtolower puts all the characters in a string to lowercases


    Case of a "strlen"
    Hidden Text click here to show


    [URL="http://tutoriliez.eb2a.com/aze.php"]test code[/URL]

    Case of a "str_replace"
    Hidden Text click here to show


    [URL="http://tutoriliez.eb2a.com/testphp2.php"]test code[/URL]

    We need to specify 3 parameters:
    1. The string we're looking for. Here, one searches for "b " (one would find a word too).
    2. The string we want to put in place. Here, we put the "p" instead of "b ".
    3. The string in which we must do the research.


    Case of a "str_shuffle"

    Hidden Text click here to show

    [URL="http://tutoriliez.eb2a.com/azerty.php"]test code[/URL]

    Case of a "strtolower"
    Hidden Text click here to show


    [URL="http://tutoriliez.eb2a.com/testphp4.php"]test code[/URL]

    We will discover the function that returns the time and date. It is date (a catchy name,easy to remember). This function can give much information. The key parameters to know are :

    • H : return the hours
    • i : return the minutes
    • d : return the days
    • m : return the months
    • Y : return the years


    you can get a specific info like just the year of the month like this

    Hidden Text click here to show

    or we can get the entire thing using this piece of code :

    Hidden Text click here to show


    [URL="http://tutoriliez.eb2a.com/timedate.php"]test code[/URL]

    in this example im gonna show you how to use the function mail() at the lvl of localhost
    Hidden Text click here to show

    im not gonna put a test code page caus this 1 will spam me an email each time someone click on it , at least now you know how to work,once we reach the database level im gonna show u guys some examples using mail function (retring lost password , encrypt your password and finally the confirm registration by clicking on the link on ur mail), ye sounds that few cool things are coming up

    that's it for now see you on the next lesson the Arrays.

    p.s: in case of images fail i've uploaded them bellow , regards Arbalest
    Last edited by Arbalest; 25th December 2010 at 03:36 PM.

  10. #10
    the roXor <3 Arbalest's Avatar
    Join Date
    Jan 2008
    Location
    above
    Age
    37
    Posts
    1,015

    Arrays

    here,we begin here an important aspect of PHP : the array.
    You will see that these "composed" variables,which it can be imagined as a table.

    You can do many things with the array and its use, it'ss not always easy.
    However, they will very quickly become indispensable and you understand the way it works.
    If you succeed, we toured the basics of PHP and you'll be ready for the next sequel, which promises to be practical and exciting.
    with this lesson we'll close the first Part of this Tutorial and start up with the Next Part
    transmitting data

    The two types of tables

    Hidden Text click here to show


    Arrays Browsing
    Hidden Text click here to show

    a quick display of an array with print_r
    Hidden Text click here to show


    Search into an array
    Hidden Text click here to show

    you guys probably noticed that there is some design changes in the lesson from now on i'll do it this way
    that's it for now see u all in a next lesson
    Last edited by Arbalest; 9th January 2011 at 09:32 PM.

  11. #11
    灰伯爵的忌廉遐想 KeweLi's Avatar
    Join Date
    Dec 2005
    Location
    Hong Kong
    Posts
    1,353
    Just dropping by. Good effort in teaching here. Some opinions:
    - Too many instructions (learners may feel turned off when seeing long pages). You can do this by separating the threads into topics. SQL and PHP should be first explained separately as you don't have to have to other to run one.
    - Maybe setup an FTP account where users can put their files on to test and play with. That will save them the effort of having to install PHP, Apache..etc. There are many cheap and free webhosts out there.

  12. #12
    the roXor <3 Arbalest's Avatar
    Join Date
    Jan 2008
    Location
    above
    Age
    37
    Posts
    1,015
    Quote Originally Posted by KeweLi View Post
    Just dropping by. Good effort in teaching here. Some opinions:
    - Too many instructions (learners may feel turned off when seeing long pages). You can do this by separating the threads into topics. SQL and PHP should be first explained separately as you don't have to have to other to run one.
    - Maybe setup an FTP account where users can put their files on to test and play with. That will save them the effort of having to install PHP, Apache..etc. There are many cheap and free webhosts out there.
    first thx for the interest
    about the origination i already thought of a new style which won't make the post too long i already made a sample in here [url]http://eurobattle.net/showthread.php?t=130035[/url]
    about seperating the topics it's already include within titles in general i entend to make 3 parts 1st @ php, 2nd a whole section for just db (mysql) when i'll start it i'll make it as a video i guess it would make a lot more clear then text and images, and the last part would be a bit more advanced combination of both php and mysql.coming with the ftp i thought of making it a small contest when it the tutorial i reach some good knowlge that would allow making a good thing something like a protect page by password which would be as soon as finish the next 2 lesson a mini-chat blog,(in the 2nd part with some db knowlege ) and at last the masterpiece a whole script with register,login and members sessions.
    at first i droped the contest when cen couldn't help me anyore in this and i droped the tutorial since i had a really busy timing anyway by all means i'm glad to inform those who are still interested in the subject that i intend to retake it and who knows when the (others section mod will be nominated) i'll revive it with quizz,contests and some icons if i could

  13. #13
    Registered User themos's Avatar
    Join Date
    Aug 2011
    Location
    Brazil
    Posts
    24

    Thumbs up Great Job!

    I don't know if you allow me to post, so tell me if I can't.
    Just want to say you did a great job!
    Plus, I think I found some minor mistakes, check them out:



    In Associative Arrays (post #10):
    Hidden Text click here to show


    In array_key_exists (post #10):
    Hidden Text click here to show


    In in_array (post #10):
    Hidden Text click here to show


    Once again, very nice work!
    Sorry for bothering.
    Last edited by themos; 15th September 2011 at 12:07 PM.




  14. #14
    the roXor <3 Arbalest's Avatar
    Join Date
    Jan 2008
    Location
    above
    Age
    37
    Posts
    1,015
    it's oki themos you can write anything u want , i'm glad u like it

  15. #15
    Registered User batata's Avatar
    Join Date
    Aug 2011
    Location
    Belgrade
    Age
    34
    Posts
    18
    ofc we like it type more if you know ^^

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  

Affiliates