SitePoint Sponsor

User Tag List

Page 8 of 8 FirstFirst ... 45678
Results 176 to 186 of 186
  1. #176
    SitePoint Zealot the DtTvB's Avatar
    Join Date
    Jul 2006
    Location
    Thailand
    Posts
    162
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Many people may use this:
    Code:
    $sql = "SELECT * FROM table";
    $result = mysql_query($sql);
    if (!$result)
        die ("<b>SQL: </b> $sql<br /><b>Error: </b>" . mysql_error());
    Shorter Version:
    Code:
    if (!$result = mysql_query($sql = "SELECT * FROM table"))
        die ("<b>SQL: </b> $sql<br /><b>Error: </b>" . mysql_error());

  2. #177
    SitePoint Zealot the DtTvB's Avatar
    Join Date
    Jul 2006
    Location
    Thailand
    Posts
    162
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Note: Really Rare Technique!

    A really short if, then, else (yeah, you can't use echo here!)
    PHP Code:
    $z 5;
    $z == ? print '$z is 5' : print '$z is not 5'
    A really short if, then (you can't use echo here too, so use print!)
    PHP Code:
    $z 5;
    $z == && print '$z is 5'
    This technique is useful when writing this code:
    PHP Code:
    get_error() && die('An error has occured!');
    // Error and die! 
    A really short if not, then (you can't use echo here too, so use print!)
    PHP Code:
    $z 4;
    $z == || print '$z is not 5'
    This technique is useful when writing this code:
    PHP Code:
    check_secess() || die('An error has occured!');
    // Sucess or die! 

  3. #178
    SitePoint Member
    Join Date
    Aug 2006
    Posts
    1
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    [QUOTE=the DtTvB]Note: Really Rare Technique!

    A really short if, then, else (yeah, you can't use echo here!)
    PHP Code:
    $z 5;
    $z == ? print '$z is 5' : print '$z is not 5'
    A really short if, then (you can't use echo here too, so use print!)
    PHP Code:
    $z 5;
    $z == && print '$z is 5'
    This technique is useful when writing this code:
    PHP Code:
    get_error() && die('An error has occured!');
    // Error and die! 
    You call it a rare technik?
    It rather reminds me of programming on basic.
    What are you gonna do when you're done with thу script? you'll have to clear all this "prints" manually. It certainly suits for small scripts, but not if you have above 500 lines.

    Debugger - that's what you need. Best of all is dbg - free debugger
    It has a commercial version built in PhpED
    PhpED is costy, but let's you forget about "print" - debugging and majority php-mysql problems.

    Oops. Looks like shameless advertizing. I'm sorry. But I really am a devoted PhpED user and am not ashamed of it.

  4. #179
    SitePoint Enthusiast
    Join Date
    Jun 2006
    Posts
    32
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    In very big projects, I like simulating namepaces for a better API and code overview!

    Instead of:

    PHP Code:
    function getGbEntries()
    {
     ...
    }
    function 
    displayGbEntries($ary)
    {
     ...
    }

    $rows getGbEntries();
    displayGbEntries($rows); 
    Rather do:

    PHP Code:
    class GB
      
    function getEntries()
      {
        ..
      }
      function 
    display($rows)
      {
        ..
      }
    }
    $rows GB::getEntries();
    GB::display($rows); 
    PHP self does not allow using real namespaces, but with this method, you can simulate them. I like this technique very very much!

    and please yes, do a summary of all good posts

  5. #180
    SitePoint Zealot
    Join Date
    Jul 2006
    Posts
    101
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Here's a tip that has really helped me. Try using a text editor that lets you navigate functions.

    I found this when using Notepad++ (a free text editor). I had just put all my functions into a separate file and then found that if you select the Plugins menu, then Function List and click View List it brings up a box with a list of all the function names in the file. If you click on a function name it moves you to the start of that function.

    This has been a revelation to me for moving around my code and keeping my head around what functions I have.

  6. #181
    SitePoint Zealot
    Join Date
    Jul 2006
    Posts
    101
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I have finished pulling this thread apart, cutting out duplicate tips, none tips and formatting it (I added BBCode for bold, italic, links, code, etc...).

    I am as yet not very experienced with PHP/MySQL so I erred on the side of caution with regards to leaving stuff in. Having said that my brain turned to mush from shear boredom a number of times so I'm not making any promises.

    I've categoried it and put linked comments close to each other so if a Mentor wants to it should be easy to cut/add any bits I missed. I saved it as plain text (including BBCode) so it should be easy to post in a new thread or whatever the Mentors want to do with it:

    MySQL

    Misc

    Strings

    Globals

  7. #182
    SitePoint Wizard holmescreek's Avatar
    Join Date
    Mar 2001
    Location
    Northwest Florida
    Posts
    1,707
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi All,

    I wrote up a long tutorial on using php with templates a while back. Anyways, I posted to a message over in the php forum today, and since it is pretty simplified (vs my original tutorial) figured I would go ahead and post it here. It should give anyone with general php knowledge how to implement simple templates.

    Cheers!


    The big advantage is that you can create your template with an html editor, so it is really easy to change the file around with the editor vs, having to come back into your php script. And for a lot of code, it beats the heck out of having to escape all the characters in a php string!

    Placing lots of html into a php string within the php script itself can be a pain and a pain to update :

    // just imagine a lot of html here, its really a pain to have
    // to escape all that html into a php string
    // and what if you did a complex form, it takes forever to modify
    // the text string to add new fields etc.

    $mystring = "<b>Hello $name</b>";



    What I suggest is creating a .tpl file, using something like dreamweaver. The .tpl file is nothing but a plain .html file.

    For the sake of argument create a form in dreamweaver, or your favorite html editor and save it as mymessage.tpl :

    <b>Hello {NAME} from {STATE}</b>


    Next, in your php script use something like this :

    PHP Code:

    <?php 

    function get_template_from_file($filename) { 


       if(
    is_file($filename)) { 
          
         
         
    // some files break this for some reason or the other 
          // I commented the below out until I get the chance to figure 
          // out what is going on with it. 
         
         /* 
           ob_start(); 
           include($filename); 
           $contents = ob_get_contents(); 
           ob_end_clean(); 
          */ 
           
          // use standard file read instead of the above 
           
          
    $fp fopen($filename,"r"); 
           
          while(!
    feof($fp)){ 
           
            
    $contents .= fgets($fp,1024); 
           
          } 
           
          
    fclose($fp); 


           return 
    $contents
       } 
       return 
    "Sorry the requested file was not found!"



    // read template, replace {NAME} with $their_name and store in
    // $output_str 


    $their_name "John Doe"
    $their_state "Florida";

    $template_name "mymessage.tpl"
    $output_str get_template_from_file($template_name);

    // replace the {SOMETHING} fields with the appropriate variable values
     
    $output_str str_replace("{NAME}",$their_name,$output_str); 
    $output_str str_replace("{STATE}",$their_state,$output_str); 


    //This reads the mymessage.tpl file, replaces all occurences of {NAME} 
    //with $their_name and replaces all occurences of {STATE} with the value
    // of $their_state


    // When you get ready to output it just use :

    echo $output_str;

    ?>
    intragenesis, llc professional web & graphic design

  8. #183
    SitePoint Member
    Join Date
    Sep 2006
    Posts
    4
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Showing Confirmation/Error Messages in Web Apps

    Just wanted to submit a quick tip about passing confirmation messages, etc.

    I've been working on a complicated app that has many different messages displayed to users (for confirmation, errors, for validation, etc).

    I'm sure there's better ways to do this, but I came up with a quick function to help me out.

    Note: you must be using SESSIONS to use this function.

    Check it out....

    PHP Code:
    function showMessage($msg "")
    {
        if (
    $msg == "" && isset($_SESSION['showMessage']))
        {
            echo 
    $_SESSION['showMessage'];
            unset(
    $_SESSION['showMessage']);
        }
        
        if (
    $msg != "")
        {
            
    $_SESSION['showMessage'] = $msg;
        }


    This function takes one argument: $msg.

    If passed with a string, like 'showMessage("Foo")', it sets the string in a session variable, that can be displayed later. And since it's stored in SESSION, that means anywhere (on any page) later.

    If, like me, you have a standard location on your page for displaying the messages, you just call the function without any arguments, like 'showMessage();', and it will display whatever message was previously set, and then unset the session variable, so that it doesn't get displayed again on accident.

    I know it's very, very basic - but I just wanted to present the idea.

    There are ways to change this to make it much more compatible with the Model/View/Controller idea as well - such as 'returning' the string, rather than simply echoing it, adding options to generate/echo CSS/HTML wrappers, etc.

    Like I said, a simple idea. It happened to be all I needed at the time.

    If you have a better way to do this, definitely share it. If anyone's interested, I'm sure they'd just love you for it. = )

    Thanks,

    Tommy George
    Last edited by tommygeorge.com; Oct 6, 2006 at 09:12. Reason: Code correction.

  9. #184
    SitePoint Zealot
    Join Date
    Jul 2006
    Posts
    101
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    This is a way to get an associative array when using a prepared statement. The tricky part is how to pass $stmt->bind_result an array. The solution is to use call_user_func_array.

    PHP Code:
    $mysqli = new mysqli($dbHost$dbUsername$dbPassword$dbDatabase);
    $stmt $mysqli->prepare('select * from foobar');
    $stmt->execute();
    $stmt->store_result();

    // this returns info about the query, script uses the 
    // $meta->name to create an array with the key's as
    // the column names
    $meta $stmt->result_metadata();

    // this needs to be $bindVarArray[] = &$results[$column->name];
    // rather than $results[$column->name] = NULL, when using 
    // call_user_func_array it needs the &, I'm not sure why
    while ($column $meta->fetch_field()) {
        
    $bindVarArray[] = &$results[$column->name];
    }        
    call_user_func_array(array($stmt'bind_result'), $bindVarArray);

    $stmt->fetch();

    echo 
    var_dump($results);
    // outputs:
    // 
    // array(3) {
    //  ["id"]=>
    //  &int(1)
    //  ["foo"]=>
    //  &string(11) "This is Foo"
    //  ["bar"]=>
    //  &string(11) "This is Bar"
    // } 
    As an asside I have been supprised how easy prepared statements are to use. With the extra security they give (SQL injection protection) it is worth checking them out. This tutorial is what got me into them, a good read!

    John

  10. #185
    SitePoint Addict Skookum's Avatar
    Join Date
    Sep 2006
    Location
    Idaho
    Posts
    375
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I just went cross-eyed reading all of the posts in this thread, and I must say I never want to hear about Global Variables again

    Here is some code to help with Session security. It helps with guessing of Session ID's and some XSS that can hijack Session ID's
    PHP Code:
    define('UA_SEED');
    session_start();
    if(!isset(
    $_SESSION['created'])){
        
    session_regenerate_id();
        
    $_SESSION['created'] = TRUE;
    }
    if(!isset(
    $_SESSION['user_agent'])){
        
    $_SESSION['user_agent'] = md5($_SERVER['HTTP_USER_AGENT'] . UA_SEED);
    }
    else{
        if(
    $_SESSION['user_agent'] != md5($_SERVER['HTTP_USER_AGENT'] . UA_SEED)){
            Echo 
    "There was an error with the information your browser provided this website<br>";
        }

    And here is a function that I read about that is suppose to keep people from reading your files when you are on a shared webserver and are unable to move your password files out of the web directories, or change the path in your PHP.ini
    PHP Code:
    $selfparts split('/'$_SERVER['PHP_SELF']);
    $file ereg_replace('\\\\''/'__FILE__);
    $fileparts split('/'$file);

    if(
    $selfparts[count($selfparts) - 1] == $fileparts[count($fileparts) - 1]){
        Echo 
    "You have caused a general protection fault on this website<br>";
        Echo 
    "Error Number:  1998";
        exit;

    Hope these can help someone, also I have to say thanks to the people in this forum as they have helped me out so much.

    Thanks All.
    Paranoia is no longer a mental illness it is a way of life - Me

  11. #186
    SitePoint Member
    Join Date
    Mar 2006
    Posts
    16
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    if tou need all weeks or Mondays that passed from some date until now, this might be useful


    PHP Code:
    <?php

    /*
    #  getWeeks function;
    #  author: Dragan Bajcic
    #  http://hosaka.blogspot.com
    #  usage: getWeeks(2006,2) - returns an array of all mondays since second week of 2006
    # inspired by: http://www.php.net/manual/en/function.date.php#68269
    */

    function getWeeks($year,$week_no){
       
    $week 0;
       
    $day 2;
       
    $mo 1;
       
    $mondays = array();
       
    $today=time();
       
    $i =$week_no;
       
    $test =  strtotime(date("r"mktime(000$mo,$day$year)) . "+" $i " week");
     
       while (
    $today >= $test) {

           
    array_push($mondays,date("d-m-Y"$test));
             
    $i++;
           
    $test =  strtotime(date("r"mktime(000$mo,$day$year)) . "+" $i " week");

       }
       return 
    $mondays;
    }
    /*
    #######################################################
    # Get all weeks and mondays starting from week #45,2006
    #######################################################
    */
    $mondays=getWeeks(2006,45);


    print 
    "weeks:<br/>";
    foreach (
    $mondays as $ws){

       echo 
    date("d M Y"strtotime($ws))." - ".date("d M Y",strtotime($ws)+(7*24*60*60))."<br/>";

    }

    print 
    "mondays:<br/>";
    foreach (
    $mondays as $ws){

       echo 
    date("d M Y"strtotime($ws))."<br/>";

    }

    /*output:

    weeks:
    20 Nov 2006 - 27 Nov 2006
    27 Nov 2006 - 04 Dec 2006
    04 Dec 2006 - 11 Dec 2006
    mondays:
    20 Nov 2006
    27 Nov 2006
    04 Dec 2006


    */

    ?>
    Last edited by kodi; Dec 9, 2006 at 07:32.
    my little Blog


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
  •