Page 1 of 8 123 ... Last
  • Jump to page:
    #1
  1. Banned (not really)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Dec 1999
    Location
    Brussels, Belgium
    Posts
    14,648
    Rep Power
    4493

    Answers to Frequently Asked Questions. Newbies read!!


    NOTE: This FAQ is out of date. There is a new document that contains a FAQ and a general purpose new user guide, please use that instead




    In addition to the guidelines for posting given by JeffCT , this thread covers the answers to Frequently Asked Questions, or FAQs.

    I’ll allow replies to this post as long as they are in the same question / answer format and are simple to understand. Any others will be deleted. Message me if you have issues.

    Generally the answer to your question is in the manual.
    PHP Manual: http://www.php.net/manual/en/
    MySQL Manual: http://www.mysql.com/documentation/mysql/bychapter/

    PHP functions are given in lowercase, MySQL functions are given in UPPERCASE.
    Most of the database issues will deal with MySQL since that’s what most questions deal with.

    #1. Why doesn’t this work?
    This is useless. First of all, what if everyone posted like this?
    http://fbg.ignitedns.com/devshed_ugh.html (Thanks JeffCT)
    The point is to have a topic that says what your problem is. This forum would be useless, otherwise, because no one wants to read every single question with no idea what the problem is. Then also go on and give as much information as possible in the text of your question.

    Before posting, though, you have to do a little debugging and tracing on your own. Step through your code piece by piece and try to narrow down where the error is. Put in extra code to print out values wherever you need to see the values of variables, to make sure it’s what it’s supposed to be.

    Something I’ve started doing is including a small table at the beginning of each page where I print out $QUERY_STRING and use print_r() on _POST, _GET, _COOKIE, and _SESSION so I can see what values are being passed and used within the page. Control this by a global variable in an include file for whether it’s shown or not. That way you can turn “debugging mode” on and off easily.

    #2. Why isn’t my form data showing up?
    I have a text box called name but $name doesn’t have a value on the next page… Make sure register_globals in on in your php.ini file. It is off by default in PHP 4.2+. If it's off, you’ll have to use $_POST['name'] or $_GET['name'] depending on the method of your form.

    #3. I tried the code you gave, but it didn’t work. Why?
    #4. I found this script but it doesn’t work. Why?
    You generally can’t just cut and paste code and expect it to work on your machine. People give you answers on here so that you can see how it’s done, now exactly how you should do it. Tear apart their answer and adapt to your needs. You might have to change variable names or table and column names in queries, etc.

    #5. How do I use sessions?
    First of all, so many session questions are answered in the user comments in the manual errata. Read through all of those first.

    Second, to do anything with sessions, you must call session_start(). To use session_destroy(), you must first call session_start. Then, to save variables in the session, you call session_register(“Variable_Name”). Notice it’s not session_register($Variable_Name) Whatever value that variable has at the end of the script will be saved and made available on any page that uses session_start().

    If you destroy a session, the variables are still available for the rest of the script. It doesn’t unset() them for you.

    UPDATE: Sessions are even easier with PHP 4.2 and register globals OFF. All you have to do is call session_start() on each page you want the session variables available. Then, you just treat the $_SESSION variable as any other variable. When you assign something like $_SESSION['name'] = "John", you now have the $_SESSION['name'] variable available to you on any page that has session_start on it. It is that simple. To "erase" a session variable, simply use unset($_SESSION['name']);

    #6. I’m trying to pass a variable in the url, but it only passes the first word. Why?
    You can’t pass spaces in URLs. If $var = “Hello World”; and you try to pass it as somepage.php?var=$var, then you’ll only get up to the space. Use rawurlencode() or urlencode to convert the spaces and other symbols into something that can be passed through the url. There is no need to decode the variable in the receiving page.
    PHP Code:
    $var "This contains a space";
    location "newpage.php?var=" urlencode($var); 
    #7. Why is only the first word of my variable showing up in my text box?
    This goes right along with the answer above and the answer on strings.

    <input type=text name=address value=<?$address?>>
    <input type=’text’ name=’address’ value=’<?=$address?>’>

    If $address has a space in it, then how can the text box determine where the “value” starts and ends. After the space in the first text box, it starts to see anything as additional attributes of the box. For the second one, it sees everything between the quotes as the value. Going along with the string questions, if $address has a single quote in it, then the text box will see everything up to that quote as the value, and ignore the rest. Quotes within textbox values must be converted into HTML entities, such as &amp;quot;.
    PHP Code:
    $var "This & \"That\"";
    echo 
    "<input type=text name=var value='" htmlentities($var) . "'>"
    #8. Why can’t I insert time() into the database?
    MySQL and PHP use different time formats. PHP uses the unix format, which is the number of seconds since the Unix Epoch (Jan 01 1970 00:00:00 GMT). MySQL uses a format such as YYYYMMDDHHMMSS or YYYY-MM-DD HH:MM:SS (the second is a string).

    You can use FROM_UNIXTIME() or UNIX_TIMESTAMP() in your queries to convert between the two. You can also use DATE_FORMAT() in your query to format your dates. It’s similar to date() in PHP.

    #9. Why does my variable lost it’s value inside my function?
    Variable Scope. Variables created inside of functions are different than the ones outside of it. Use global to make it the same variable in both, or pass it to the function.
    PHP Code:
    function do_me($var)
    {
        global 
    $test
    Changes to $var will not affect a $var on the outside of the function. Changes to $test will, because it’s global.

    #10. What is an Invalid Result Resource ?
    When you get this error it generally means your database query has failed for some reason. Unfortunately, your query can fail, but the database or PHP won’t give you an error as to why. This is where mysql_error() comes in. This will return the error that MySQL generated for your query. A good habit to get into is to use a setup like this:
    PHP Code:
    $query “SELECT FROM table WHERE id $id”;
    $result mysql_query($query) or die(“SELECT Error“ mysql_error() . “ in Query$query”); 
    #11. How do I get the results from a database query?
    #12. How come my result only prints out Resource ID#1?
    When you issue a query such as the one above and assign the result to a variable, say $result, it basically assigns a link to the result to the variable. So you can’t just print out the variable and expect everything to be there. This is where the mysql_fetch_*() functions come into play.
    mysql_fetch_rowFetches a row from the result into an array. $row = mysql_fetch_array($result); You then use $row[0] for the first column returned from the query, $row[1] for the second, etc.
    mysql_fetch_arraySame as _fetch_row, except you can now use the name of the column as the key in the array. If you use a query such as SELECT name,age FROM table, then $row[name] would contain the name, and $row[age] would contain the age. You can also use $row[“name”] or $row[‘name’] or even $row[0] (for the first column)
    mysql_fetch_objectSame as above except an object is returned. See the manual.

    #13. How do I get the AUTO_INCREMENT id of the row just created?
    If you have an AUTO_INCREMENT column in your table, when you insert a new row, it’s automatically assigned a new number.
    PHP Code:
    $result mysql_query(“INSERT INTO table (idnamevalues (null,’John’)); 
    To get the number just created you can do two things. If you need it in PHP, you can do this:
    PHP Code:
    $last_id mysql_insert_id($link_id); 
    Where $link_id is what’s returned from mysql_connect(…). It’s optional.

    If you need the number in MySQL, perhaps to use in other tables to link back to the first row, then you can use this
    PHP Code:
    $result mysql_query(“INSERT INTO table2 (id2addressVALUES (LAST_INSERT_ID(), ‘222 Someplace Lane’));
    $result2 mysql_query(“INSERT INTO table3 (id3whateverVALUES (LAST_INSERT_ID(),’Whatever’)); 
    This will insert the AUTO_INCREMENT number from table into BOTH table2 and table3. (So long as table2 or table3 don’t have an AUTO_INCREMENT column.) This is because the last_id is specific for your connection (script) and is the same until another AUTO_INCREMENT number is generated.

    Comments on this post

    • LinuxPenguin agrees : Happy Christmas
    • gimp agrees
    • carrie_a_tune agrees : Christmas cheer! You rock! :)
    • dotancohen agrees : I should have read these a long time ago.
    Last edited by ManiacDan; April 10th, 2011 at 02:15 AM. Reason: linking to the new faq
  2. #2
  3. Banned (not really)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Dec 1999
    Location
    Brussels, Belgium
    Posts
    14,648
    Rep Power
    4493
    #14. My data doesn’t sort correctly. Why does 10 come before 2?
    You’re using varchar fields or text fields, aren’t you? As integers, numbers would come in this order: 1,2,3,10,20,30,100,200,300.

    Compared as text, they come in this order:
    1
    10
    100
    2
    20
    200
    3
    30
    300

    #15. How can I do this query ______ in PHP?
    Any query you give to MySQL on the command line, you can give you MySQL through PHP and the results will be exactly the same. The column names will be the same. Issue the query through mysql_query().

    #16. My random number generator doesn’t work or it returns the same number each time. Why?
    You have to “seed” random number generators. They are not truly random, they return a sequence of numbers and by “seeding” them, you start from different areas in that sequence. If you seed it with the same number each time, you’ll get the same sequence. This can be useful for debugging. Use the mt_srand() or srand() functions for seeding. There are examples in the manual.

    UPDATE: This behavior has changed in PHP 4.2.0+. You no longer have to "seed" the random number generator before you call rand() or mt_rand().

    #17. I get an error whenever I try to insert something with an ‘ in it into the database. Why
    Strings are surrounded by quotes. Either single or double, they give the limits of the string. Now if there’s the same kind of quote within the string, how does PHP know where the real end is?
    PHP Code:
    $string “Molly said “hi” when she saw me”
    PHP sees $string = “Molly said “ and then it tries to interpret the rest as code.

    Same goes with inserting things into MySQL. If you surround your variables with single quotes, and there’s a single quote in the variable, where is the end?

    Use addslashes() to escape single and double quotes within strings. Magic_quotes (controlled in php.ini) will automatically escape quotes in form data.

    #18. When I delete a row, the AUTO_INCREMENT number isn’t reused. How can I reuse it?
    Bottom line is you don’t want to. All an AUTO_INCREMENT column should be used for is a unique identifier for each row. It’s what distinguishes each row from one another, since no two can ever be the same. Don’t use it to see how many rows are in the table, use COUNT() for that. If this is a problem for some reason, you’re using the column for the wrong reason. There is a PHP or MySQL function that does what you’re looking for regardless of the holes.
  4. #3
  5. Banned (not really)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Dec 1999
    Location
    Brussels, Belgium
    Posts
    14,648
    Rep Power
    4493
    #19. What is the best editor to use for PHP?
    They're all basically text editors, aren't they? Some have line numbers, some use color highlighting, some don't. What do you need?

    The only recommendation that I would follow is to get something with line numbers. This is very handy when debugging your code and trying to find the Parse error on Line 405.

    Here is one thread on the options.
    Here is a list of editors you can download.

    #20. Should I use echo or print?
    Doesn't matter, they are the same.

    print "Hello";
    echo "Hello";

    You can use paranthesis if you want.

    print ("Hello");

    print will return true if was able to print of not. The only useful purpose this would have is to see if the user terminated the connection (according to comments in manual), but there are functions for that, already.
  6. #4
  7. Banned (not really)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Dec 1999
    Location
    Brussels, Belgium
    Posts
    14,648
    Rep Power
    4493
    #21. I get a parse error on the last line of my file, but it's just the </html>. Why?
    #22. Why do I get a parse error on Line #xx, but there's nothing wrong with that line?
    The line number that PHP gives you is where if finally realized that something is wrong with the code and it couldn't proceed. It's doesn't mean that's exactly where the error is at. The error can be at any point in the code before that line.

    Missing a closing bracket somewhere in your code will cause you to get PHP saying there is an error on the very last line of the file. the only way to find your missing bracket is to pick through your code. Missing a semi-colon or quote can also cause errors in lines that are after the line with the actual error.
    PHP Code:
    echo "This is missing an end quote;
    $var = 1 + 3;
    do_this(
    $var);
    echo "
    Error will be herethough"; 
    In this example, PHP will look at everything from the first double quote in the first echo, to the first double quote in the second echo as a string. Once it closes the string, it'll see Error will ... and come up with a parse error, since those aren't valid PHP functions. So the error line will be reported on the second echo line, but the actual error is on the first echo line.
  8. #5
  9. funky munky
    Devshed Beginner (1000 - 1499 posts)

    Join Date
    Jul 2001
    Location
    UK
    Posts
    1,446
    Rep Power
    16
    #23. I need help with regular expressions!
    Regular expressions can be surprisingly easy to master with the right information at hand.

    The syntax of Perl Compatible Regular Expressions (or PCRE to acronym fans;\) is discussed in the manual, as are the PHP regular expression functions. However the PHP manual is perhaps not the best place to start if you are new to the subject of regular expressions.

    Below are some links to various resources for all things regexp, listed in order of usefulness:
  10. #6
  11. No Profile Picture
    PerlGuy
    Devshed Novice (500 - 999 posts)

    Join Date
    Jan 2001
    Posts
    720
    Rep Power
    42
    Kudos. Great Post guys.
    - dsb -
    Perl Guy
  12. #7
  13. No Profile Picture
    Php Slave
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2002
    Posts
    475
    Rep Power
    13
    Great posts indeed.
    There are no mistakes in life....only lessons!
  14. #8
  15. Mobbing Gangster
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Sep 2001
    Location
    "Best City" 2002 and 2003- Melbourne, Australia
    Posts
    4,912
    Rep Power
    33
    #24 How do I make prev/next links?

    General code would be something like this:
    PHP Code:
    mysql_connect('localhost','user','password') or die('cant connect');
    mysql_select_db('one');


    $perPage=1;
    $start=isset($HTTP_GET_VARS['s'])?$HTTP_GET_VARS['s']:0;
    $total_rows=isset($HTTP_GET_VARS['t'])?$HTTP_GET_VARS['t']:'';
    $PHP_SELF=isset($HTTP_SERVER_VARS['PHP_SELF'])?$HTTP_SERVER_VARS['PHP_SELF']:'';

    if(!
    $total_rows)
        list(
    $total_rows)=mysql_fetch_row(mysql_query('select count(*) from user'));

    $result=mysql_query("select * from user limit $start,$perPage");

    while (
    $data=mysql_fetch_assoc($result)) 
        echo 
    $data['username'];//output data here

    $startP=$start-$perPage;
    echo 
    $startP>=0"<a href='$PHP_SELF?t=$total_rows&s=$startP'>PREV</a>  " 'PREV  ';

    $startN=$start+$perPage;
    echo 
    $startN<$total_rows "<a href='$PHP_SELF?t=$total_rows&s=$startN'>NEXT</a>  " 'NEXT  ';?> 
    Several things you need to be aware of:
    Firstly, as you see I've decided to pass total # of records through url in sake of saving some time and load for mysql and not requesting to count rows every time. I do not think this could cause any problems, but it surely will take the load off of sql db.

    And secondly, you can as well make it work through POST so that none of the variables show up in the URI, but it is up to you to decide which is *the way*, personally I dont see any advantages of one over another. Good luck reaching max url size with just search keywords.

    edited for better code
    Last edited by Sepodati; June 26th, 2005 at 09:31 PM.
    And you know I mean that.
  16. #9
  17. Mobbing Gangster
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Sep 2001
    Location
    "Best City" 2002 and 2003- Melbourne, Australia
    Posts
    4,912
    Rep Power
    33
    #25 How do I separate data from mysql by categories?
    aka I need to group data from mysql together.

    This is a simple task indeed, and doesn't require a lot of changes to your code. Here is a sample code to get information from the sample table which looks like
    ---------------------------------------------------
    | id | home | away | score | tournament |
    ---------------------------------------------------
    And I need to get that information and put all games in the same tournament under the title on tournament and do that for each group of games.
    PHP Code:
    <?php
    mysql_connect
    ('localhost','user','pass');
    mysql_select_db('myDB');
    $q=mysql_query('select * from mytable order by tournament');
    while(
    $r=mysql_fetch_assoc($q)) {
      if(
    $prevT!=$r['tournament']) {
        echo 
    '<br>Tournament <b>'.$r['tournament'].'</b><br>';
        
    $prevT=$r['tournament'];
      }
      echo 
    $r['home'].' vs '.$r['away'].' '.$r['score'].'<br>';
    }
    ?>
    As you see not much code at all, but this is fairly FAQ.
    And you know I mean that.
  18. #10
  19. Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Apr 2001
    Posts
    645
    Rep Power
    0
    I want to add that in #2 it has changed some and I think it needs updated here as well.

    #2. Why isn’t my form data showing up?
    I have a text box called name but $name doesn’t have a value on the next page…

    ok, first you shouldn't use name as your name for the text box. some browsers have problems sorting this out, considering it is the attribute for the textbox, and should be avoided. try $nname if you want. On php version 4.2 and above, the register_globals is off in your php.ini file. It should be by default, for security reasons. If it is and you don’t have any control over it, then you’ll have to use $HTTP_POST_VARS[name] or $HTTP_GET_VARS[name] depending on the method of your form. although those variables still work, they are deprecated, meaning that they might not be in the newest and latest version of php. you should use the super globals listed in the manual, HERE


    #26. Why do I get the error "Headers already sent out"?
    generally it is because you sent something to the screen before your header() function was executed, (or session_start(), setcookie(), etc). it can be a number of things but the first that comes to mind is - you need to always have the setcookie() at the top of your code, before you have anything going to the screen, even <html> will give you that error. also the header() function acts the same way. Another reason might be that you have a space *before* <?php of your code. If you have your header() up top, the <? has to be the very first line, even before any !DOCTYPE or it will cause the error as well.

    UPDATE: The warning message tells you everything you need to know.
    Warning: Cannot add header information - headers already sent by (output started at c:\inetpub\wwwroot\test.php:3) in c:\inetpub\wwwroot\test.php on line 5
    Notice the "ouput started at" part. This error tells you that test.php started some output on line 3. Now you can track down where the output is being started from if you don't now.
    Last edited by Sepodati; July 12th, 2005 at 09:54 PM.
  20. #11
  21. No Profile Picture
    Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2001
    Posts
    10
    Rep Power
    0
    #27 What is CHMOD and how does it relate to PHP?

    CHMOD relates to providing file permissions so you can read/write to a file on your web space.

    Visit http://catcode.com/teachmod/ for a great on-line tutorial.
  22. #12
  23. No Profile Picture
    Web.Dev.
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2001
    Location
    Nottingham, UK
    Posts
    68
    Rep Power
    14
    #28 Can you do this script for me?

    Short: No (well, you might get really lucky, but I doubt it )

    Long: You may find it dificult to believe, because of some of the great guys (and girls) here at DevShed Forums, but generally people are not willing to write a complete script, and I doubt most people here will heavily modify a script you have found on some other site.

    We are here to help with PHP coding (and PHP logic), not to write peoples scripts. So please learn as much as you can about PHP, then if you come across a problem, people are more than willing to help.

    Remember: People who help you, have jobs, and lives, and not enough time to write complete PHP Applications for enyone else willy-nilly.

    If you wish to recrute someone's PHP skills, and pay them to PHP. Please do so in an orderly manor and Private Message (PM) them.


    Brent

    Note to Mods: Feel free to delete this post if you feel it is not generaly true, or not relative to the subject
  24. #13
  25. Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Feb 2000
    Location
    Perth West Australia
    Posts
    757
    Rep Power
    15
    #29 Why does my page and/or javascript not work in $browser_type

    A - I dont know, but it has nothing to do with PHP, if your page renders differently in different browsers then thats a HTML/CSS or javascript issue NOT a PHP one, check you HTML code and appreciate that some browsers work differently from others.

    If your PHP generated javacscript does not work then again its a javascript issue NOT a PHP one, PHP only outputs the javascript to your browser, view the source of your generated page to work out what and where the errors are.

    Javascript is clientside, PHP is serverside, so do not expect any PHP code to be executed by a javascript event, by the time the user sees your javascript PHP is already doing something else somewhere else!
  26. #14
  27. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2002
    Posts
    3
    Rep Power
    0

    #30 How do i str_replace thats not case sensitive


    #30 How do i str_replace thats not case sensitive

    PHP Code:
    /* Was submitted by jpenn : Senior Member */

    function stri_replace$find$replace$string )
        {
        
    $parts explodestrtolower($find), strtolower($string) );

        
    $pos 0;

        foreach( 
    $parts as $key=>$part )
            {
            
    $parts$key ] = substr($string$posstrlen($part));
            
    $pos += strlen($part) + strlen($find);
            }

        return( 
    join$replace$parts ) );
    }

    echo 
    stri_replace$find$replace$string ); 
  28. #15
  29. Contributing User
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Jun 2002
    Location
    Washington, DC
    Posts
    2,692
    Rep Power
    22
    #31 Why is the unset() function not working with $_SESSION['variables'].....

    Unsetting a $_SESSION['variable'] with registered globals turned to 'off' in your PHP ini file can be accomplished like so ->
    PHP Code:
    unset( $_SESSION['variable'] ); 
    If registered globals is turned to 'on' in your ini file, you can use one of the two following methods to unset your $_SESSION['variable'] ->

    Function posted by RodK
    PHP Code:
    function unreg_sess_varstring $element )
        {
        if ( 
    ini_get'register_globals' ) )
            {
            
    session_unregister$element );
        } else
            {
            unset( 
    $_SESSION[$element] );
        }
    }

    unreg_sess_var$_SESSION['variable'] );  /* ( REPLACE WITH YOUR VARIABLE )---- */ 
    Posted by SilkySmooth
    PHP Code:
    unset( $_SESSION['variable'], $variable ); /* ( REPLACE WITH YOUR VARIABLE )---- */ 
    Note that both of the above methods will work with registered_globals turned on or off......


    UPDATE
    From an email from bugs.php.net.....

    The above is true only for 4.2.2 and below. unset( $_SESSION['variable'] ) will unset the varaible w/ or without registered_globals turned on in versions 4.2.3 and above...

    ANOTHER UPDATE
    From an email from bugs.php.net.....

    The problem still exists in 4.2.3. So, use the above solutions if you are having this problem.....
    ~ Joe Penn
Page 1 of 8 123 ... Last
  • Jump to page:

IMN logo majestic logo threadwatch logo seochat tools logo