November 8th, 2001, 10:26 PM
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.
#7. Why is only the first word of my variable showing up in my text box?
$var = "This contains a space";
location = "newpage.php?var=" . urlencode($var);
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 &quot;.
#8. Why can’t I insert time() into the database?
$var = "This & \"That\"";
echo "<input type=text name=var value='" . htmlentities($var) . "'>";
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.
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:
#11. How do I get the results from a database query?
$query = “SELECT * FROM table WHERE id = $id”;
$result = mysql_query($query) or die(“SELECT Error: “ . mysql_error() . “ in Query: $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 for the first column returned from the query, $row 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 (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.
To get the number just created you can do two things. If you need it in PHP, you can do this:
$result = mysql_query(“INSERT INTO table (id, name) values (null,’John’)”);
Where $link_id is what’s returned from mysql_connect(…). It’s optional.
$last_id = mysql_insert_id($link_id);
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
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.
$result = mysql_query(“INSERT INTO table2 (id2, address) VALUES (LAST_INSERT_ID(), ‘222 Someplace Lane’)”);
$result2 = mysql_query(“INSERT INTO table3 (id3, whatever) VALUES (LAST_INSERT_ID(),’Whatever’)”);
Comments on this post
Last edited by ManiacDan; April 10th, 2011 at 02:15 AM.
Reason: linking to the new faq
November 8th, 2001, 10:30 PM
#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:
#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 sees $string = “Molly said “ and then it tries to interpret the rest as code.
$string = “Molly said “hi” when she saw me”;
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.
November 9th, 2001, 11:31 AM
#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.
You can use paranthesis if you want.
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.
November 14th, 2001, 06:41 AM
#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.
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.
echo "This is missing an end quote;
$var = 1 + 3;
echo "Error will be here, though";
December 10th, 2001, 06:03 PM
#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:
February 5th, 2002, 11:47 AM
- dsb -
There are no mistakes in life....only lessons!
June 10th, 2002, 08:16 PM
#24 How do I make prev/next links?
General code would be something like this:
Several things you need to be aware of:
mysql_connect('localhost','user','password') or die('cant connect');
list($total_rows)=mysql_fetch_row(mysql_query('select count(*) from user'));
$result=mysql_query("select * from user limit $start,$perPage");
echo $data['username'];//output data here
echo $startP>=0? "<a href='$PHP_SELF?t=$total_rows&s=$startP'>PREV</a> " : 'PREV ';
echo $startN<$total_rows ? "<a href='$PHP_SELF?t=$total_rows&s=$startN'>NEXT</a> " : 'NEXT ';?>
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.
June 12th, 2002, 03:28 PM
#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.
As you see not much code at all, but this is fairly FAQ.
$q=mysql_query('select * from mytable order by tournament');
echo '<br>Tournament <b>'.$r['tournament'].'</b><br>';
echo $r['home'].' vs '.$r['away'].' '.$r['score'].'<br>';
And you know I mean that.
June 13th, 2002, 03:55 PM
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.
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.
July 11th, 2002, 11:24 AM
#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.
July 14th, 2002, 12:11 PM
#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.
Note to Mods: Feel free to delete this post if you feel it is not generaly true, or not relative to the subject
August 8th, 2002, 11:41 AM
September 9th, 2002, 06:35 AM
#30 How do i str_replace thats not case sensitive
#30 How do i str_replace thats not case sensitive
/* Was submitted by jpenn : Senior Member */
function stri_replace( $find, $replace, $string )
$parts = explode( strtolower($find), strtolower($string) );
$pos = 0;
foreach( $parts as $key=>$part )
$parts[ $key ] = substr($string, $pos, strlen($part));
$pos += strlen($part) + strlen($find);
return( join( $replace, $parts ) );
echo stri_replace( $find, $replace, $string );
September 21st, 2002, 01:21 PM
#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 ->
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'] ->
unset( $_SESSION['variable'] );
Function posted by RodK
Posted by SilkySmooth
function unreg_sess_var( string $element )
if ( ini_get( 'register_globals' ) )
session_unregister( $element );
unset( $_SESSION[$element] );
unreg_sess_var( $_SESSION['variable'] ); /* ( REPLACE WITH YOUR VARIABLE )---- */
Note that both of the above methods will work with registered_globals turned on or off......
unset( $_SESSION['variable'], $variable ); /* ( REPLACE WITH YOUR VARIABLE )---- */
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...
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