SitePoint Sponsor

User Tag List

Results 1 to 20 of 20
  1. #1
    John 8:24 JREAM's Avatar
    Join Date
    Sep 2007
    Location
    Florida
    Posts
    1,508
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Some PHP Tips for Beginners

    Hey guys, here are a few tips that might help you, that in my opinion would be good to consider!

    1. Use MySQLi functions instead of MySQL functions
    You can use the functions procedurally or as an object, so the learning curve is very easy. A lot of the functions have very similar names. With MySQLi you can create prepared statements, you might not need them right now, but the option will be good later on. If you want to get a better head start than this, I would recommend learning PDO, but that has a hard learning curve.
    http://php.net/manual/en/book.mysqli.php

    2. Use descriptive camelCase $variables
    A regular variable can be confusing if you read your own code later, $myvar or $item does not make much sense, unless you want to re-study your code a year later! So try to be descriptive and camelCase variables, it is a popular naming convention used in Java and Zend Framework. A variable would be something like this: $inputFileName
    http://framework.zend.com/manual/en/...nventions.html

    3. Master the Array's and Multi-Dimensional Arrays
    You will work with arrays a lot and they have a lot of power. When you understand how to re-arrange things and grab what you need you will see they are life-savers in many situations!

    Tip: If you don't assign a key, it will use a digit by default
    PHP Code:
    // Enumerated arrays (Digits are used for the key)
    $b = array ('dog''cat''fish'10 => 255);
    echo 
    $b[0]; // Gives you dog
    echo $b[255// Gives you an error, because 255 is the value not they key!
    $variable['key'] = 'value'

    // Associative arrays (Words used for the key)
    $c = array ('fish' => 'big''dog' => 'fat')
    echo 
    $c['fish'// Gives you 'Big'
    echo $c[0// Gives you an error, the keys are associative not enumerated.

    // Multi-Dimensional Array (An array that has more arrays in it)
    $d = array('cat' => array(
         
    'brown'
         
    'yellow'
         
    'black'), 
        
    'dog' => 'none');

    echo 
    $d['cat'][0// Grabs 'brown'
    echo $d['cat']['yellow'// Error, yellow is the value! 
    echo $d['dog'// Gives you 'none' 
    Some great array functions to start with:
    array_pop
    array_shift
    array_slice
    implode
    explode
    * and some of the sorting ones

    http://php.net/manual/en/ref.array.php


    4. Comment your code
    You don't have to get obsessive over it, but it might save you a lot of sweat from your forehead someday trying to figure out what you were doing. An example of a comment is with phpDoc and it looks like this:

    PHP Code:
    /**
    * @desc  This function does nothing 
    */
    function Nothing()
    {
        return 
    0;

    Alternatively you can also name all your arguments like this:
    PHP Code:
    /**
    * @desc  This function does nothing 
    * @var <str> $strInput An input string that does nothing right now...
    */
    function Nothing($strInput)
    {
        return 
    0;

    This way you can write your projects documents while you program it. It takes a little effort and habit to get into, but it is going to help you someday.

    5. When you are bored, practice OOP
    Objects will change your programming life and make you capable of many more things. It is tricky to learn at first, and tricky to see the value at first. But after a few months of doing OOP you will be one of the happiest people alive.

    Even if you don't totally understand what you are doing, doing a little bit each day will stick in your mind and you'll be able to recall things you've read about and the understanding comes together like building blocks.

    http://www.php.net/manual/en/language.oop5.basic.php

    6. Ask stupid questions if Google wont help you
    Its easiest to ask a question where your problem rests, rather than sending a huge 300 line copy paste I noticed when you ask short and simple questions people are on it like a dog on a raw bone, they want to be the first to answer. But people tend to avoid the lengthy long questions where they must dig through a ton of code. So try to find where your error lies, and keep it simple.

  2. #2
    SitePoint Wizard bronze trophy chris.upjohn's Avatar
    Join Date
    Apr 2010
    Location
    Melbourne, AU
    Posts
    2,189
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    Nice tips JREAM, arrays and multi-dimensional arrays is a winner to know as from experience its one of the most helpful codes PHP has to store heaps of info :P

  3. #3
    SitePoint Mentor bronze trophy
    John_Betong's Avatar
    Join Date
    Aug 2005
    Location
    City of Angels
    Posts
    1,808
    Mentioned
    73 Post(s)
    Tagged
    6 Thread(s)
    Maybe download te documentation from http://www.php.net/docs.php

    start of every project:
    PHP Code:

       set error_level
    (E_ALL); 
       
    ini_set('display_errors','On'); 
    I find that trying to get rid of the warnings is the best way to learn the language.

  4. #4
    Twitter: @AnthonySterling silver trophy AnthonySterling's Avatar
    Join Date
    Apr 2008
    Location
    North-East, UK.
    Posts
    6,111
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by John_Betong View Post
    Maybe download te documentation from http://www.php.net/docs.php

    start of every project:
    PHP Code:

       set error_level
    (E_ALL); 
       
    ini_set('display_errors','On'); 
    I find that trying to get rid of the warnings is the best way to learn the language.
    Great advice, that's exactly what I do

    PHP Code:
    <?php
    error_reporting
    (-1);
    ini_set('display_errors'true);
    @AnthonySterling: I'm a PHP developer, a consultant for oopnorth.com and the organiser of @phpne, a PHP User Group covering the North-East of England.

  5. #5
    It's all Geek to me silver trophybronze trophy
    ralph.m's Avatar
    Join Date
    Mar 2009
    Location
    Melbourne, AU
    Posts
    24,120
    Mentioned
    448 Post(s)
    Tagged
    8 Thread(s)
    Quote Originally Posted by John_Betong View Post
    Maybe download te documentation
    Ah wow, thanks, I didn't know about that.
    Facebook | Google+ | Twitter | Web Design Tips | Free Contact Form

    Forum Usage: Tips on posting code samples, images and more

    Forrest Gump: "IE is like a box of chocolates: you never know what you're gonna get."

  6. #6
    SitePoint Mentor bronze trophy
    John_Betong's Avatar
    Join Date
    Aug 2005
    Location
    City of Angels
    Posts
    1,808
    Mentioned
    73 Post(s)
    Tagged
    6 Thread(s)
    Quote Originally Posted by AnthonySterling View Post
    Great advice, that's exactly what I do

    PHP Code:
    <?php
    error_reporting
    (-1);
    ini_set('display_errors'true);
    Whoops, it has been a long day sweating over the keyboard

    PHP accepts the 'On' parameter in ini_set('display_errors', 'On'), why use true and why do you set the parameter to -1 instead of E_ALL? Am I missing something?

  7. #7
    Twitter: @AnthonySterling silver trophy AnthonySterling's Avatar
    Join Date
    Apr 2008
    Location
    North-East, UK.
    Posts
    6,111
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    Pretty sure E_ALL doesn't include strict, the docs state -1 reports ALL errors, so that'll do for me.

    Why true? The setting is blatantly a boolean, so I use true. Just personal semantics I guess.
    @AnthonySterling: I'm a PHP developer, a consultant for oopnorth.com and the organiser of @phpne, a PHP User Group covering the North-East of England.

  8. #8
    Utopia, Inc. silver trophy
    ScallioXTX's Avatar
    Join Date
    Aug 2008
    Location
    The Netherlands
    Posts
    9,039
    Mentioned
    152 Post(s)
    Tagged
    2 Thread(s)
    Huh, that's weird.

    PHP Code:
    ini_set('display_errors'$var); 
    If you set $var to true it will display the errors, if you set it to false it won't.
    If you set it to 'On' it will display the errors, which is to be expected since (bool)'On' is true. However, if you set to 'Off' (which is also logically true) it doesn't display the errors.

    It seems the code is something like this:

    Code:
    function ini_set($key, $value)
    {
       if ($value==='Off') $value=false;
       // set internal value here
    }
    As for the error_reporting -1, AFAIK that does indeed mean ALL possible errors. Now, and in the future. That is, if there are ever levels added above E_STRICT these will be thrown as well.
    Rémon - Hosting Advisor

    Minimal Bookmarks Tree
    My Google Chrome extension: browsing bookmarks made easy

  9. #9
    Twitter: @AnthonySterling silver trophy AnthonySterling's Avatar
    Join Date
    Apr 2008
    Location
    North-East, UK.
    Posts
    6,111
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    It looks like this is the logic used...

    'static PHP_INI_DISP(display_errors_mode)', lines 303 -> 347.

    Lines 262 -> 289 looks pretty interesting too, they detail how PHP re-reads the user supplied setting.
    @AnthonySterling: I'm a PHP developer, a consultant for oopnorth.com and the organiser of @phpne, a PHP User Group covering the North-East of England.

  10. #10
    SitePoint Mentor bronze trophy
    John_Betong's Avatar
    Join Date
    Aug 2005
    Location
    City of Angels
    Posts
    1,808
    Mentioned
    73 Post(s)
    Tagged
    6 Thread(s)
    I run WAMP and call http://localhost in my browser.

    Another useful setting is to define a LOCALHOST variable.

    LOCALHOST is used throughout my scripts to cater for different configurations when the scripts are uploaded to the server.

    PHP Code:
      
      
    if(! defined('LOCALHOST')) // prevent error if already defined
      
    {
         
    define('LOCALHOST''localhost' === $_SERVER['SERVER_NAME']);
      }

      
    // PHP errors and warnings are logged but not visible to punters.
      
    error_reporting(-1); // catch all including E_STRICT

      // The ini_set(...) when used online prevents any errors 
      // and especially paths from showing 
      // on the off-chance an error is encountered.
      
    ini_set('display_errors',LOCALHOST);



      
    // mysql online defaults settings
      
    $dbhost 'my_host';
      
    $dbase  'online_database_name';
      
    $dbuser 'online_user_name';
      
    $dbpass 'online_password';
      if(
    LOCALHOST)
      {
        
    $dbhost 'my_localhost';
        
    $dbase  'localhost_database_name';
        
    $dbuser 'localhost_user_name';
        
    $dbpass 'localhost_password';
      }
      
       
    $dbh=mysql_connect
       
    (
          
    $dbhost 'my_localhost';
          
    $dbuser 'localhost_user_name';
          
    $dbpass 'localhost_password';
       )
       or die(
    'Cannot connect to the database because: ' mysql_error());
       
    mysql_select_db($dbase); 
    The above code eliminates the need to have two configuration files
    and especially uploading the wrong file and over-writing the online configuration file.
    Last edited by John_Betong; Dec 1, 2010 at 08:38. Reason: grammar is not my fortey

  11. #11
    Twitter: @AnthonySterling silver trophy AnthonySterling's Avatar
    Join Date
    Apr 2008
    Location
    North-East, UK.
    Posts
    6,111
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by John_Betong View Post
    Another useful setting is to define a LOCALHOST variable.

    LOCALHOST is used throughout my scripts to cater for different configurations when the scripts are uploaded to the server.
    Have you thought about just having one, central, point for this change in behaviour?

    PHP Code:
    <?php
    error_reporting
    (-1);
    ini_set('display_errors'true);

    define(
      
    'IS_PRODUCTION',
      
    true
    );

    $config ConfigurationFactory::Build(
      
    IS_PRODUCTION 'production.ini' 'development.ini'
    );

    ?>
    @AnthonySterling: I'm a PHP developer, a consultant for oopnorth.com and the organiser of @phpne, a PHP User Group covering the North-East of England.

  12. #12
    I solve practical problems. bronze trophy
    Michael Morris's Avatar
    Join Date
    Jan 2008
    Location
    Knoxville TN
    Posts
    2,023
    Mentioned
    63 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by JREAM View Post
    1. Use MySQLi functions instead of MySQL functions
    No. Use PDO. There's a movement in the dev group to remove all of the older db access libraries out of PHP Core and into PECL starting with PHP 5.4, which means they will not always be available because they won't be compiled into all distributions, probably starting around PHP 6.1

    2. Use descriptive camelCase $variables
    More importantly, follow conventions. $i is a generic incrementing index of a loop, if loops are nested then $j, then $k is used. Variable names that have to be typed a LOT need to be shorter. Abstract functions can and should have abstract variable names.

    Constants are ALL_CAPS. Class names should be capitalized, functions are never capitalized. Older PHP code (4 or earlier) starts method and member names with an _ to mark that they are private or protected - don't do this, actually make them private or protected.

    Camel case isn't the only way - underscores_are_just_as_valid.

    Quote Originally Posted by ScallioXTX View Post
    As for the error_reporting -1, AFAIK that does indeed mean ALL possible errors. Now, and in the future. That is, if there are ever levels added above E_STRICT these will be thrown as well.
    Like E_DEPRECATED, E_USER_DEPRECATED (As of PHP 5.3)

    My advice is to read this and try not to accidentally do anything it mentions by mistake: http://freeworld.thc.org/root/phun/unmaintain.html

  13. #13
    Utopia, Inc. silver trophy
    ScallioXTX's Avatar
    Join Date
    Aug 2008
    Location
    The Netherlands
    Posts
    9,039
    Mentioned
    152 Post(s)
    Tagged
    2 Thread(s)
    Quote Originally Posted by AnthonySterling View Post
    Have you thought about just having one, central, point for this change in behaviour?
    Instead of defining it in every project separately I have it defined in the PHP auto_prepend_file on my development PC.

    PHP Code:
    define('IS_DEV_SERVER'true); 
    and then in the project bootstrap I have

    PHP Code:
    defined('IS_DEV_SERVER') or define('IS_DEV_SERVER'false); 
    And then just check in the code for defined('IS_DEV_SERVER') && IS_DEV_SERVER for things that should only be ran on development servers (extended logging, different configurations, etc)

    The advantage of this is that if you ever decide to add more development servers you can just copy the auto_prepend_file to the new server and all websites running there switch to development mode instantly.

    Of course on a live server IS_DEVELOPMENT_SERVER isn't defined , so projects running there will never be in development mode, unless I define IS_DEV_SERVER to be true for a particular project.

    I guess you could say this is a generalization of the solution John_Betong uses
    Rémon - Hosting Advisor

    Minimal Bookmarks Tree
    My Google Chrome extension: browsing bookmarks made easy

  14. #14
    SitePoint Wizard silver trophybronze trophy Cups's Avatar
    Join Date
    Oct 2006
    Location
    France, deep rural.
    Posts
    6,869
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    7 Don't let the cat in the room with you

    It will only start accidentally typing with its foot/tail, and you should be aware of the risk that it might write better code than you, deflating your ego. Also, they molt hairs everywhere which can get between the keyboard keys or make you sneeze.

  15. #15
    SitePoint Mentor bronze trophy
    John_Betong's Avatar
    Join Date
    Aug 2005
    Location
    City of Angels
    Posts
    1,808
    Mentioned
    73 Post(s)
    Tagged
    6 Thread(s)
    Quote Originally Posted by Michael Morris View Post
    ...
    ...
    ...
    My advice is to read this and try not to accidentally do anything it mentions by mistake: http://freeworld.thc.org/root/phun/unmaintain.html

    The link is absolutely hilarious and raised frequent belly laughs nearly bringing tears to my eyes.

    This is my favourite:
    Reverse the Usual True False Convention

    Reverse the usual definitions of true and false. Sounds very obvious but it works great. You can hide:
    #define TRUE 0
    #define FALSE 1
    somewhere deep in the code so that it is dredged up from the bowels of the program from some file that noone ever looks at anymore. Then force the program to do comparisons like:
    if ( var == TRUE )
    if ( var != FALSE )
    ...
    ...
    ...

  16. #16
    SitePoint Mentor bronze trophy
    John_Betong's Avatar
    Join Date
    Aug 2005
    Location
    City of Angels
    Posts
    1,808
    Mentioned
    73 Post(s)
    Tagged
    6 Thread(s)
    Originally Posted by AnthonySterling
    Have you thought about just having one, central, point for this change in behaviour?
    Instead of defining it in every project separately I have it defined in the PHP auto_prepend_file on my development PC.

    ...
    ...
    ...

    and

    Originally Posted by ScallioXTX
    ...
    ...
    ...

    I guess you could say this is a generalization of the solution John_Betong uses
    As mentioned by Cups there are many ways to skin a cat

    The original post was "Some PHP Tips for Beginners" but now it is getting a bit too hairy for beginners.

  17. #17
    John 8:24 JREAM's Avatar
    Join Date
    Sep 2007
    Location
    Florida
    Posts
    1,508
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Michael Morris View Post
    No. Use PDO. There's a movement in the dev group to remove all of the older db access libraries out of PHP Core and into PECL starting with PHP 5.4, which means they will not always be available because they won't be compiled into all distributions, probably starting around PHP 6.1
    Wow that'd be cool. I suggest mysqli because PDO is a more difficult learning curve, but it's worth it to go the distance

  18. #18
    SitePoint Wizard bronze trophy Immerse's Avatar
    Join Date
    Mar 2006
    Location
    Netherlands
    Posts
    1,661
    Mentioned
    7 Post(s)
    Tagged
    1 Thread(s)
    Quote Originally Posted by ScallioXTX View Post
    Instead of defining it in every project separately I have it defined in the PHP auto_prepend_file on my development PC.

    PHP Code:
    define('IS_DEV_SERVER'true); 
    Ooh, that's a very clever solution to the 'to debug or not to debug' question.
    I think I'll copy that!

  19. #19
    SitePoint Evangelist
    Join Date
    Aug 2010
    Posts
    503
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by John_Betong View Post
    I run WAMP and call http://localhost in my browser.

    Another useful setting is to define a LOCALHOST variable.

    LOCALHOST is used throughout my scripts to cater for different configurations when the scripts are uploaded to the server.

    PHP Code:
      
      
    if(! defined('LOCALHOST')) // prevent error if already defined
      
    {
         
    define('LOCALHOST''localhost' === $_SERVER['SERVER_NAME']);
      }

      
    // PHP errors and warnings are logged but not visible to punters.
      
    error_reporting(-1); // catch all including E_STRICT

      // The ini_set(...) when used online prevents any errors 
      // and especially paths from showing 
      // on the off-chance an error is encountered.
      
    ini_set('display_errors',LOCALHOST);



      
    // mysql online defaults settings
      
    $dbhost 'my_host';
      
    $dbase  'online_database_name';
      
    $dbuser 'online_user_name';
      
    $dbpass 'online_password';
      if(
    LOCALHOST)
      {
        
    $dbhost 'my_localhost';
        
    $dbase  'localhost_database_name';
        
    $dbuser 'localhost_user_name';
        
    $dbpass 'localhost_password';
      }
      
       
    $dbh=mysql_connect
       
    (
          
    $dbhost 'my_localhost';
          
    $dbuser 'localhost_user_name';
          
    $dbpass 'localhost_password';
       )
       or die(
    'Cannot connect to the database because: ' mysql_error());
       
    mysql_select_db($dbase); 
    The above code eliminates the need to have two configuration files
    and especially uploading the wrong file and over-writing the online configuration file.
    This is such a useful thing to know. I've bumped into this problem several times, never thought about it really but this would prove very useful. I'll have a play with it later. Cheers for the tip.

  20. #20
    SitePoint Mentor bronze trophy
    John_Betong's Avatar
    Join Date
    Aug 2005
    Location
    City of Angels
    Posts
    1,808
    Mentioned
    73 Post(s)
    Tagged
    6 Thread(s)
    Quote Originally Posted by coxdabd View Post
    This is such a useful thing to know. I've bumped into this problem several times, never thought about it really but this would prove very useful. I'll have a play with it later. Cheers for the tip.
    I noticed an error with the script, try this instead:
    PHP Code:

     
    // mysql online defaults settings 
      
    $dbhost 'my_host'
      
    $dbase  'online_database_name'
      
    $dbuser 'online_user_name'
      
    $dbpass 'online_password'
      if(
    LOCALHOST
      { 
        
    $dbhost 'my_localhost'
        
    $dbase  'localhost_database_name'
        
    $dbuser 'localhost_user_name'
        
    $dbpass 'localhost_password'
      } 
       
       
    $dbh=mysql_connect ($dbhost$dbuser$dbpass
       or 
       die(
    'Cannot connect to the database because: ' mysql_error()); 

       
    mysql_select_db($dbase); 


Bookmarks

Posting Permissions

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