1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

PHP Basics in 6 Days

Discussion in 'PHP' started by RogerDodgr, Aug 11, 2007.

  1. #1
    Hi, I am a total newb to PHP (as you will see). I wanted to start a thread where other learners could join in, and critique each-others scripts. Maybe, more knowledgeable members can stop in and offer a tip or challenge us to write a simple script. I am studying trough a book titled, "PHP and MySQL for Dynamic Websites, 2nd ed.", but you could be learning from any source; I’d be glad to hear form you. I have until the 17th to get the basics of PHP before school starts. Here is my first script; I know it's lame, but I have to start somewhere. Hope to be further along by the 17th.

    
    <?php
    $i =100;
    while ( $i>=1 ) {
        echo "$i  bottles of beer on the wall, <br>";
        echo "$i  bottles of beer,... <br> take one down pass it around, ";
        $i--;
    
        if ($i >= 1){
        echo "$i  bottles of beer on the wall <br><br>";}
        else {echo "<b>someone go to the store!</b>";}
    }
    ?>
    
    Code (markup):

     
    RogerDodgr, Aug 11, 2007 IP
  2. Dirty-Rockstar

    Dirty-Rockstar Guest

    Messages:
    252
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    0
    #2
    LMAO thats funny. Ill give you my first few scripts i ever made. Not as funny as yours


    <?
    
    $Number=rand(1,100);
    
    
    print "$Number";
    
    ?>
    PHP:

    
    <?
    
    $Number=rand(1,100);
    $Divide = $Number / 2;
    
    print "$Number
    <br>
    $Divide";
    
    ?>
    PHP:

    
    <?
    
    
    $Number=$_POST[entry];
    $entry=$Number / 2;
    $picked_number="The number you picked was<br><b> $Number</b><br>";
    $result="Dividing it by two is <br><b>$entry</b>";
    
    if(!isset($Number)) { $picked_number="<b>Input any number into the box below</b>"; $result="<b>Your number will be divided by 2 and shown here</b>"; }
    
    print "
    <center>
    <table>
    <tr>
    <td align=center valign=middle>
    
    $picked_number
    <br><br>
    <form method='post' action=test.php>
    
    
    <input type='text' name='entry' value='$Number' maxlength='10'><br><br>
    <input type='submit' name='submit' value='Divide'>
    </form>
    $result
    
    
    </td>
    </tr></table>";
    
    
    
    ?>
    PHP:
     
    Dirty-Rockstar, Aug 11, 2007 IP
  3. Cesay

    Cesay Peon

    Messages:
    121
    Likes Received:
    9
    Best Answers:
    0
    Trophy Points:
    0
    #3
    
    <?php
    $i =100;
    while ( $i>=1 ) {
        echo "$i";
        echo ($i > 1) ? "bottles" : "bottle";
        echo "of beer on the wall, <br>";
        echo "$i  bottles of beer,... <br> take one down pass it around, ";
        echo ($i > 1) ? "" : "No more bottles of beer on the wall. Someone go to the store!";
        $i--;
    }
    ?>
    
    Code (markup):
    :)
     
    Cesay, Aug 11, 2007 IP
  4. void

    void Peon

    Messages:
    119
    Likes Received:
    9
    Best Answers:
    0
    Trophy Points:
    0
    #4
    "1 bottles of beer,..." ;)
     
    void, Aug 11, 2007 IP
  5. ecentricNick

    ecentricNick Peon

    Messages:
    351
    Likes Received:
    13
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Fantastic idea. I am always impressed by people trying to learn rather than just posting "fix my script" or "write this for me".

    You asked for challenges, so here goes with challenge #1

    Write the following:

    You need a script containing a form with a single input field (or a text area) into which the user can type something.

    On clicking the submit button the form will post back to itself, and will print the entered string out....but backwards.

    The form will again be displayed below this so another string can be entered.

    Optionally, the form should still contain what the user entered last time.

    lol, i feel like an exam setter - you get a distinction for the last bit!!
     
    ecentricNick, Aug 11, 2007 IP
  6. RogerDodgr

    RogerDodgr Well-Known Member

    Messages:
    267
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    105
    #6
    Thanks guys, good catch on the plurals and DirtyRockstar, that helped with a question I had about forms.
    This was also helpful: echo ($i > 1) ? "bottles" : "bottle"; I wrote it down inside my book. I played with every script posted and learned from them, thanks! I'm now moving from chapter 2 on "programming" and into chapter 3 on "creating dynamic web sites".

    Ch 3:
    -include multiple files
    -handling HTML forms with PHP Redux
    -Making sticky forms
    -creating and calling your own functions
    -variable scope
    -date and time functions
    -sending email

    I'll butcher some more code tommorow. If someone wants to challenge me to write a simple script, I'm up for the challenge!
     
    RogerDodgr, Aug 11, 2007 IP
  7. exodus

    exodus Well-Known Member

    Messages:
    1,900
    Likes Received:
    35
    Best Answers:
    0
    Trophy Points:
    165
    #7
    
    <?
    for($i=100;$i >= 1; $i--)
    {
        echo "$i ";
        echo ($i > 1) ? "bottles" : "bottle";
        echo " of beer on the wall... $i  bottles of beer... take one down pass it around... <br />";
        echo ($i > 1) ? "" : "No more bottles of beer on the wall. Someone go to the store!";
    }
    ?>
    
    PHP:
    Simple way of doing
    
    echo ($blah > 4) ? "true" : "false";
    
    PHP:
    this thing.
    
    if($blah > 4)
    {
      echo "true";
    }
    else
    {
      echo "false";
    }
    
    PHP:
    For a beginer. I suggest you learn the different between print and echo. Then learn the different of a single quote verses a double qoute.

    $blah = 'exodus';
    $var = "$blah is my name";
    $var2 = '$blah is my name';
    $var3 = $blah." is my name";

    etc.

    Then I would move onto the if / elseif / else
    Then I would move onto the for loop
    Then I would learn the while loop
    Then I would learn the mixing of html and php.
    .... :p
     
    exodus, Aug 11, 2007 IP
  8. Cesay

    Cesay Peon

    Messages:
    121
    Likes Received:
    9
    Best Answers:
    0
    Trophy Points:
    0
    #8
    Whoops. Er, I meant to do that. :eek:
     
    Cesay, Aug 11, 2007 IP
  9. RogerDodgr

    RogerDodgr Well-Known Member

    Messages:
    267
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    105
    #9
    Thanks EcentricNick, I think I got it! It's actually a cool yet weird little script. Maybe it could be used for something. I may fix it up a bit, or if anyone wants to make a correction, feel free. I posted it in the link below; check it out if you get a chance, and thanks for the challenge.

    http://www.fuelefficiency.org/test/test2.php


    
    
    <?php
    $word = stripslashes($_POST['word']);
    echo "<b>$word </b>";
    
    $w_commas = chunk_split($word,1,",");
    
    $exploded = (explode(",",$w_commas));
    
    Krsort($exploded);
    
    $backwards = implode("",$exploded);
    echo "<br><b> $backwards";
    
    ?>
    
    
    <form action="test3.php" method="post">
    	<fieldset><legend>Enter a word or phrase to be reversed:</legend>
    	<p><b>Word:</b> <input type="text" name="word" size="20" maxlength="40" value="<?php if (isset($_POST['word'])) echo $_POST['word']; ?>" /></p>
    	</fieldset>
    	<div align="center"><input type="submit" name="submit" value="Reverse My Word" /></div>
    </form>
    
    
    
    Code (markup):
     
    RogerDodgr, Aug 11, 2007 IP
  10. exodus

    exodus Well-Known Member

    Messages:
    1,900
    Likes Received:
    35
    Best Answers:
    0
    Trophy Points:
    165
    #10
    RogerDodgr: There are a bunch of ways of doing it. This is just two of them. :)

    
    $words = 'This is a string of words';
    $len   = strlen($words);
    for($c = 0;$c >= $len - ($len*2); $c--)
    {
      echo substr($words,$c,1);
    }
    
    PHP:
    
    $words = 'This is a string of words';
    for($c = strlen($words)-1;$c >= 0; $c--)
    {
      echo $words{$c};
    }
    
    PHP:

    
    $words = 'This is a string of words';
    echo strrev($words);
    
    PHP:
     
    exodus, Aug 12, 2007 IP
  11. coderlinks

    coderlinks Peon

    Messages:
    282
    Likes Received:
    19
    Best Answers:
    0
    Trophy Points:
    0
    #11
    Go to PHP.net and check out the functions list. There are a LOT of functions in PHP. Many a time I have tried to implement some gruesome task and after completing it ended up finding out there was a single PHP function for doing the exact thing!!.

    ~
    Thomas
     
    coderlinks, Aug 12, 2007 IP
  12. ecentricNick

    ecentricNick Peon

    Messages:
    351
    Likes Received:
    13
    Best Answers:
    0
    Trophy Points:
    0
    #12
    Nice work! Yes, clearly there are a number of ways of doing it and php is so function rich that there are always a number of ways one can achieve the same thing.

    But, I chose that challenge as it requires a number of techniques that are so common to php - mainly getting information from a html form into a script and doing something with it - usually some kind of string manipulation. It may be basic stuff but how many posts do we see here from people struggling with these kind of basics?

    So, roger, do you want more challenges, or are you all coded out now?
     
    ecentricNick, Aug 13, 2007 IP
  13. Perrow

    Perrow Well-Known Member

    Messages:
    1,306
    Likes Received:
    78
    Best Answers:
    0
    Trophy Points:
    140
    #13
    On the note of handling form input I suggest this task to improve your web form security abilities. A form with three input fields, two textboxes and one that is your choise of selection device (combo box, radio buttons or list field).

    Make sure the input from one text field is only numeric.
    Make sure the input from the other field is only valid characters.
    Make sure the selection field has a value selected from the list of options.

    The last one is important, if you don't know why you should really read up on (php) security.
     
    Perrow, Aug 13, 2007 IP
  14. RogerDodgr

    RogerDodgr Well-Known Member

    Messages:
    267
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    105
    #14
    Thanks everyone. Yes ecentricNick, I'm up for a challenge,,, I'm going to do Perrow's as well. Please note the stuff I got into yesterday in Chapter 3. :)

    A lot of great comments here; appreciate all the help. The code snipets are great.

    Yesterday I got bogged down in 'chapter 3' reading ("PHP and MySQL for Dynamic Websites) which was on:
    -include multiple files
    -handling HTML forms with PHP Redux
    -Making sticky forms
    -creating and calling your own functions
    -variable scope
    -date and time functions
    -sending email

    My brain was spinning and the only thing I coded was a half-baked 'video of the day' "function" based on a date function --> date("d"). :confused: Today (day 3!), I'm going to play with code after checking on classes. I will post.
     
    RogerDodgr, Aug 13, 2007 IP
  15. ecentricNick

    ecentricNick Peon

    Messages:
    351
    Likes Received:
    13
    Best Answers:
    0
    Trophy Points:
    0
    #15
    Definitely do Perrow's first - that one is a nice challenge.

    Then, as you're covering date formats, then how about this...

    Create a form into which the user enters their date of birth - either typed in, or more preferably selecting from drop downs.

    When they submit the form, validate that it is a real date - ie. can't enter 30th February, or a date in the future etc.

    Once it's passed validation, calculate their age in years, months and days.

    For bonus point, calculate the number of days until their next birthday.
     
    ecentricNick, Aug 13, 2007 IP
  16. RogerDodgr

    RogerDodgr Well-Known Member

    Messages:
    267
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    105
    #16
    Thanks Perrow, that was a helpful article; I understood the point about someone copying a page's HTML code and then hosting it elswhere; however, I was confused at how to remedy that (I couldn't figure out the point about selection fields). I thought about putting some code in a seperate function with different variables, but that did nothing, when the HTML is stolen and referenced it still runs (I hacked my own page). I'll think about that some more.

    I was able to do some basic form validation, and I also encorporated strip_tags so people can't enter <script>malicious code</script>. The script validates numbers and also validates that the word is *not a number. (I tried validating strings, but numbers entered in a form are also considered strings by php.)

    It's hosted here: http://www.fuelefficiency.org/test/test3.php if you want to look, it's a basic compund-interest savings calculator that takes a string, two numbers, and a year (selection field); and posts validation errors.


    
    <body>
    <?php
    
    //function caculates interest and principal on investment
    function hide($gl, $yrs, $rt, $st){
        //interest formula
        $dRate = $rt/100;
        $total = $st*pow((1+($dRate/12)),(12*$yrs));
        $total = number_format($total, 2);
        
        // echo statement
        echo "<b>In $yrs ";
        echo ($yrs > 1) ? "years" : "year";
        echo" you will have \$$total saved towards a $gl</b>. <br><i>(Savings based on interest compounded monthly.)</i>";
    }
    
    $goal = stripslashes(strip_tags($_POST['goal']));
    $years = stripslashes(strip_tags($_POST['years']));
    $rate = stripslashes(strip_tags($_POST['rate']));
    $start = stripslashes(strip_tags($_POST['start']));
    
    
    
        //If form is valid and submitted: call function and send arguments
        if ( !is_numeric($_POST['goal']) && is_numeric($_POST['rate']) && is_numeric($_POST['start'])   &&  (isset ($_POST['submitted']))       ) {
            hide($goal, $years, $rate, $start); 
        }   
        
        //else prompt user...
        else{ 
            if( (isset ($_POST['submitted'])) && is_numeric($_POST['goal'])){
                echo '<b>Go back and fill in the "saving for" field with word(s).</b> ';
                }
            if(      (isset ($_POST['submitted'])) &&         !is_numeric($_POST['rate'])){
                echo '<b>Go back and fill in the "Interest Rate" field with a number.</b> ';
                }
            if(           (isset ($_POST['submitted']))           && !is_numeric($_POST['start'])){
                echo '<b>Go back and fill in the "Initial Savings" field with a number.</b> ';
                }
        } //end else prompt user
    
    ?>
    
    
    <form action="test3.php" method="post">
    	<fieldset><legend>Investment Savings Calculator:</legend>
            <p><b>What are you saving for?<br></b><input type="text" name="goal" size="20" maxlength="40" value="<?php if (isset($_POST['goal'])) echo $_POST['goal']; ?>" /></p>
            <p><b>Interest Rate:<br></b><input type="text" name="rate" size="3" maxlength="4" value="<?php if (isset($_POST['rate'])) echo $_POST['rate']; ?>" /></p>
            <p><b>Inital Savings:<br></b><input type="text" name="start" size="7" maxlength="15" value="<?php if (isset($_POST['start'])) echo $_POST['start']; ?>" /></p>
            <p><b>Investment matures in:
            <br><select name="years">
                <option value="1">1 Year</option>
                <option value="2">2 Years</option>
                <option value="3">3 Years</option>
                <option value="4">4 Years</option>
                <option value="5">5 Years</option>
            </select>
            <?php    ?>
    	</fieldset></p>
    	<div align="center"><input type="submit" name="submitted" value="Calculate My Investment" /></div>
    </form>
    
    
    </body>
    
    
    Code (markup):
     
    RogerDodgr, Aug 13, 2007 IP
  17. Perrow

    Perrow Well-Known Member

    Messages:
    1,306
    Likes Received:
    78
    Best Answers:
    0
    Trophy Points:
    140
    #17
    Nice work there Roger, handling and validating strings are important and difficult. Insuring the user enters only alpha characters can be done using regular expressions, but thats a somewhat complex area so I suggest you hold off on that.

    In your script you should ideally check that the value entered for years is a number in the range of 1 to 5. Let's say it was not years but a vote for how good your site is. If you trust the value submitted I could save your form, modify it, and submit -9237476 as my vote, and your script would gladly accept it. That is why you should do sanity checks on all input from webforms.

    I don't know how good your book is but you should really look into the function mysql_real_escape_string. You use it to make sure data submitted in a form wont harm your database when your inserting it. Again, ideally you shold rather make sure that whats submitted is valid rather that "not unvalid", meaning if the field should contain only alpha characters, you should make sure it contains only alpha characters rather than just escaping the string.
     
    Perrow, Aug 14, 2007 IP
  18. RogerDodgr

    RogerDodgr Well-Known Member

    Messages:
    267
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    105
    #18
    Hey ecentricNick, thanks, that's a fun challenge. I will be spreading this one across a couple days. I found out about checkdate, so that's a good lesson. I'll update (edit) this as it progresses, but I probably won't bump the thread. If anyone want's to look, it's at: http://www.fuelefficiency.org/test/test6.php Thanks again for the help.

    
    <form action="test6.php" method="post">
    	<fieldset><legend>Enter your birthday:</legend>
    
    <?php
    	// Make the months array.
    	$months = array (1 => 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
    	// Make the months pull-down menu.
    	echo '<select name="month">';
    	foreach ($months as $key => $value) {
    		echo "<option value=\"$key\">$value</option>\n";
    	}
    	echo '</select>';
    
    
    	// Make the days pull-down menu.
    	echo '<select name="day">';
    	for ($day = 1; $day <= 31; $day++) {
    		echo "<option value=\"$day\"";
    		echo ">$day</option>\n";
    	}
    	echo '</select>';
    
    
    	// Make the years pull-down menu.
    	echo '<select name="year">';
    	for ($year = 1900; $year <= date ('Y'); $year++) {
    		echo "<option value=\"$year\"";
    		echo ">$year</option>\n";
    	}
    	echo '</select><br>';
    
        // Print the current day and time (for testing)
        echo  'Today\'s date: '. date ('n, j, Y') . '<br>';
    
        if (isset ($_POST['submitted'])) {
            $m = stripslashes(strip_tags($_POST['month']));
            $d = stripslashes(strip_tags($_POST['day']));
            $y = stripslashes(strip_tags($_POST['year']));
    
            echo '<br>';
            echo "You entered: $m, $d, $y <br>";
    
            if (!checkdate($m, $d, $y) || //not valid date
                ($y == date('Y') && $m >date('n'))  || // future (condition 1)
                ($y == date('Y') && $m == date('n') && $d > date('j')) // future (condition 2)
                ){
                echo 'You entered an invalid date; please go back and re-enter the date.';
              } else {
              echo 'Valid date<br><br>';
              calcBday($m, $d, $y);
              }
        }
        //function caculates years, months and days between two dates
        function calcBday($mo, $da, $yr){ 
            if ($mo < date('n')){
                $thisYear = date('Y');
                $years = $thisYear - $yr;
                echo "You are $years years,";
              }
            if ($mo > date('n')){
                $thisYear = date('Y');
                $years = $thisYear - $yr -1;
                echo "You are $years years,";
              }
            }
    
        ?>
    
    	</fieldset></p>
    	<div align="center"><input type="submit" name="submitted" value="Calculate my Birthday" /></div>
    </form>
    
    PHP:


     
    RogerDodgr, Aug 14, 2007 IP
  19. JoRd

    JoRd Banned

    Messages:
    415
    Likes Received:
    13
    Best Answers:
    0
    Trophy Points:
    0
    #19
    Pardon my newbness here lol but...

    Do you guys have to write EVERY single character?! or is there something a little like dreamweaver?!

    Its just im looking to learn programming but it looks like such a daunting task!!

    Thanks
    Jord
     
    JoRd, Aug 14, 2007 IP
  20. ecentricNick

    ecentricNick Peon

    Messages:
    351
    Likes Received:
    13
    Best Answers:
    0
    Trophy Points:
    0
    #20
    Generally, Jord, every single one of 'em!

    There are code generators for some languages (may be for php too) which allow you to more or less drag and drop a objects which represent the program flow - but in reality they always limit what you can do.

    It only looks daunting at first. In the same way that a page full of French looks daunting until you start to learn French.

    But if you look back through what Roger has been doing here - he is applying an entirely logical process to solve quite well stated problems. And a lot of the constructs being used (conditional statements, looping statements, counters, variable etc) are basic building blocks you can learn in a day or so.

    Once you understand the fundamentals it all becomes much easier to read through and make sense of what you're seeing.

    It's also incredibly rewarding to do. Oh, and speaking as someone that's made a living from programming for some 25+ years, it pays really well!
     
    ecentricNick, Aug 15, 2007 IP