CMX Ads Webmaster Resources for Success

Websites, Advertising, Scripts Tips n Snippets

News: NSA Insider Reveal All

Top Php Coding errors and what to do about it

Put this snippet on the top of your trouble page and eliminate the bugs in no time.

error_reporting(E_ALL); if (!ini_get('display_errors')) { ini_set('display_errors', '1'); }

A great deal of errors are actually quite simple to and solve once you are experienced, but they continue to pop up from time to time to f with us. The following are some insights on how to solve some common problems in your code.

Source code output of my PHP script

1- This most often occurs when you have misconfigured Apache; check your install and try again.
Or as has happened to me when coding I comment out sections of code during developement and sometime the editor I suppose errors and all commented code shows?? Usually the brackets are the problem.

2- Blank white page

No output at all. Most likely you have a code error somewhere. To track it down first:

  1. Check your php.ini file and make sure "display_errors" is set to On. Or add it to the top of your page.

  2. If your script is output content inside a HTML page, the errors may be lost in the HTML - use the View Source functionality of your browser to search for "PHP". This should expose any errors, if any.

If you still have nothing, try what I do:

If you are still having trouble, you need to ask me.

3- Fatal error: Cannot redeclare (function)

All this is is that you have two functions with the same name. Sometimes I decide to put the function in the config file and forget to remove from the page it is called from.Duh! Another thing is includes. You may have the same include being called more than once. This has happened to me when when using multiple includes and forgetting to remove a function or call from one of the includes to a db class or something.

Consider this if you will!:

if ($foo > 50) { include("myfuncs.php"); }
if (
$foo > 100) { include("myfuncs.php"); }

4- Call to undefined function

This error message is simple, it means that you have called a function that cant be found.

5- Parse error

This is a very generic error message that simply means "PHP failed to understand your script", which in turn means that there is a syntax error in your script. Possible causes for this include:

6- Heredoc is not working correctly

The heredoc string syntax in PHP is very specific - one small error and it goes wrong, often in ways that are hard to understand. So, when using heredoc, you need to be particularly precise! Here’s an example of properly formed heredoc code:

<?php
    $foo
= <<<END
My text
    More text
        Even more text
END;    echo $foo;
?>

There are two things to note in there: first, the three < signs followed by the string terminator, "END". You can use anything you want in place of END, as long as you know it won’t appear in the text. Terminators are case-sensitive, unsurprisingly.

Second, the heredoc string is terminated by using END at column 0 in the code. That is, there is no text on the line before END - not even a space or a tab. So, to end your heredoc string, put your terminator at the very start of a line by itself, with a semicolon.

If you break either of these two rules, things go haywire: if you change the second END to "EnD" (note the lower-case "n"), it no longer matches as the terminator, and you’ll get an error like this:

Parse error: parse error, unexpected $end in /usr/paul/bad_heredoc.php on line 8

You’ll also get the same error if you put a single space before the terminating END. This, then, is the most common problem with heredoc: using the terminator incorrectly, or, worse, using it inside the string itself!

If you get any heredoc errors, this is what it will come down to. However, note that the error message is pretty vague: it doesn’t mention that a heredoc string wasn’t terminated, or indeed anything about strings at all. If you get an error like the one above, chances are it's either heredoc that's at fault (or other string quoting problems) or you haven’t matched up your braces properly.

7- is not a valid MySQL result index

The key to understanding this error is firstly remembering that PHP considers 0 to be the same as false, and secondly that mysql_query() returns false if the query was invalid, e.g. "SELECT * FROM usertable WHERE ORDER BY Username" - the error is that there is an empty WHERE clause.

This error is usually caused by executing a fault SQL query, then trying to work with the result (e.g. call mysql_fetch_assoc() or mysql_num_rows() ) without first having checked whether the query call succeeded.

To solve this problem, look for the query that generated the result which is causing the error. Then output the SQL of that query to your screen so you can spot the error and fix it. You may find it easiest to copy the SQL into the MySQL monitor to get it working. Alternatively, put a the statement print mysql_error() after the mysql_query() line that causes the bad result.

8- SQL query errors

Debugging SQL is much more problematic than debugging PHP code because it is hard to tell where you went wrong - particularly if it is a complex query.

Having said that, MySQL and other DBMSs will try to make your life easy by helping out where they can - if there is a problem with the query you will usually get a message back helping you in the right direction. Take a look at these next two queries and their output, for example:

mysql> SELECT * FROM mbmsg;
ERROR 1146: Table 'phpdb.mbmsg' does not exist
mysql> INSERT INTO guestbook (GuestName, GuestEmail) VALUES (, 'foo@bar.com');
ERROR 1064: You have an error in your SQL syntax. Check the manual that corresponds to your MySQL server version for the right syntax to use near ''foo@bar.com')' at line 1

The first error has a meaningful error message, and you can immediately see the problem - the mbmsg does not exist in the database phpdb. The second query is a little more tricky, though -we do not supply a value for the first parameter, which causes the error message you can see. The error message at least gets you close (although this cannot be relied upon), but debugging would be very difficult if you were working through a web browser.

Consider this if you will:

$result = mysql_query("INSERT INTO guestbook (GuestName, GuestEmail) VALUES ({$_POST['GuestName']}, {$_POST['GuestEmail']});");

Now, what would happen if we did not get GuestName sent to us as we were hoping? We would end up with the query that generated the error, and we would not be able to make sense of it because as far as we can see GuestName should be in there. Check this code:

$sql = "INSERT INTO guestbook (GuestName, GuestEmail) VALUES ({$_POST['GuestName']}, {$_POST['GuestEmail']});";
$result = mysql_query($sql);

If we find there is a problem, we can simply add echo $sql and see exactly what query is being tried out. In this situation, it is usually much easier to paste code into the MySQL monitor and try it out there - you can make changes to the SQL easily and retry it to figure out what the problem is. The monitor is also useful for testing out complex queries as it shows you immediately (and in a nicely formatted way) precisely what rows your query returned so that you can be sure it is doing what you intended it to do.

9- MySQL changes your data types

MySQL is programmed to automatically detect and optimise flawed table designs and may silently make table changes behind your back.

10- Client does not support authentication protocol

The libraries that allow PHP to communicate to a MySQL server changed as of MySQL 4.1, which some companies are already deploying. As a result, older scripts that aren’t capable of working with this new library will break if asked to connect to a 4.1 server, outputting an error like this:

PHP Warning:  mysql_connect(): Client does not support authentication protocol requested by server; consider upgrading MySQL client

MySQL doesn't change its protocol too often, so it's well worth upgrading and be done with it. Yes, you will also need to migrate your MySQL code to MySQLi code, but, again, best get it done now rather than wait until you have no choice.

11- PHP crashes!

Occasionally you will see Apache crash while trying to serve a PHP script - this is rarely Apache's fault. Instead, it is more likely to be PHP's. If PHP crashes on you, do not think it is a bug with your script - it is not. PHP should not ever crash, and if it does it is a PHP problem, not a script problem. Yes, your script might be doing something really weird or in a roundabout way, but that does not mean it should crash PHP!

Despite coming on leaps and bounds with each release, PHP is not perfect, and may crash from time to time. The only thing you can do is to try the latest version of PHP, and if the bug still exists, submit a bug report to the PHP development team at http://bugs.php.net - that way, they can fix the problem, and also help out other programmers.

12- Can’t connect to local MySQL server through socket '/tmp/mysql.sock'

This is a Unix-only problem, and usually means your MySQL server is not started or is not configured correctly. First, make sure your MySQL server is started by typing this:

ps aux | grep mysql

If you see mysqld in there somewhere, you are all go. If not, start your MySQL server (how this is done changes from distribution to distribution, but it is likely to be something like "/etc/init.d/mysql start".

Note carefully what the output of starting MySQL is - if you see any errors, make sure and try and resolve them. In a worse-case scenario you will see the server end a second or two after you start it - this is usually because you have not installed it properly, and the default authentication tables are not created. Create these by typing "mysql_install_db" as root.

In particularly odd cases, you may find that your MySQL socket is in an unusual place - that is, not where PHP would expect it to be. Try and locate your MySQL .sock file (it might be called mysql.sock or mysqld.sock), then edit your php.ini file and edit the line "mysql.default_socket" to point to the correct place.

13- I can’t get transactions to work

In any databases that contain important information, transactions become crucial to the equation. However, the default table type in MySQL (known as MyISAM) does not support them at this time, so you need to use the InnoDB table type. Earlier we did this by using this command:

CREATE TABLE foo (ID INT) TYPE = InnoDB;

That forces the InnoDB table type. If you already have a MyISAM table and want to convert it to InnoDB, you can use this:

ALTER TABLE foo Type = InnoDB;

The problem is that you may not have the InnoDB table handler installed, which means that if you ask MySQL to use the InnoDB table handler it will silently failover to the MyISAM handler - it won’t even log the error in your MySQL error log. If you find that transactions simply aren’t working for you, chances are you’re using the MyISAM handler.

To find out for sure what table handlers your tables are using, issue the command "SHOW TABLE STATUS". This prints out the names and table handlers for each of the tables in the current database - the second column is where it will say MyISAM or InnoDB. If you see "NULL" for your table type that means you had the InnoDB table handler installed at one time, created tables successfully with it, but no longer have the handler available so MySQL doesn’t understand how to use the table.

If you are specifying InnoDB but the table ends up being MyISAM, it means you do not have the InnoDB table handler available. The InnoDB table handler is included as standard with all versions of MySQL, so unless you built your own version of MySQL (not recommended!), you should have it available. However, you may not have it configured to work - if you have a my.cnf file, it may have the line "skip-innodb" in under the [mysqld] header, which disables that handler. Remove this if you have it.

The skip-innodb option may also be passed directly to the MySQL server when it is started up, so check your startup scripts for this option and remove it if it's there. If you've done these two and are definitely using the correct query to create the table, you should be able to create and use InnoDB tables easily.

If you have InnoDB tables and just can't get transactions to work, that’s a different matter entirely! Transactions have three stages: you begin the transaction, send your data, then either commit it or rollback. Here's an example transaction:

mysql> desc mytable;
+-------+----------+------+-----+---------+-------+
| Field | Type     | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| ID    | int(11)  | YES  |     | NULL    |       |
| Foo   | char(10) | YES  |     | NULL    |       |
| Bar   | char(20) | YES  |     | NULL    |       |
+-------+----------+------+-----+---------+-------+
3 rows in set (0.03 sec)

mysql> BEGIN;
Query OK, 0 rows affected (0.00 sec)

mysql> INSERT INTO mytable (ID, Foo, Bar) VALUES (1, 'Hello', 'World');
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO mytable (ID, Foo, Bar) VALUES (2, 'Wom', 'Bat');
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO mytable (ID, Foo, Bar) VALUES (2, 'PC', 'Format');
Query OK, 1 row affected (0.00 sec)

mysql> UPDATE mytable SET ID = 3 WHERE Foo = 'PC';
Query OK, 1 row affected (0.04 sec)
Rows matched: 1  Changed: 1  Warnings: 0

Note that I put the wrong ID in for the third query and corrected it with the fourth query - a transaction can contain all the usual types of queries. However, at this point nothing has actually been written to the table. You can confirm this by opening up another MySQL Monitor connection and running "SELECT * FROM mytable;". If you are indeed using InnoDB for your table handler, no rows should be returned from that query. Note that it is important to open up a new connection to the server because the connection that is actually performing the transaction does see the state of the table as if the transaction had been committed. This is necessary so that you can issue commands such as UPDATE on data that has yet to be committed.

The reason for that is because we have only completed two of the three phases of a transaction. What we have yet to do is decide whether to accept ("commit") or reject ("rollback") the transaction. For example, if we wanted to go ahead and write those three records, we’d need to send the commit "COMMIT;". That ends the transaction, and enacts all the changes you requested. With the transaction ended, you need to call BEGIN again to start a new one.

If you decide you don’t want to write the changes, you can instead call "ROLLBACK;". This essentially aborts all the changes in that transaction, and also ends it. Rolling back your transaction is saved for when one of a batch of queries goes wrong and, as a result, you’d rather not have any queries saved.

14- Warning: SAFE MODE Restriction in effect.

This warning arises when your system administrator has enabled safe mode in their php.ini file, and you are trying to do something that safe mode does not allow you to do. For example, reading files not owned by you or executing programs are both examples of operations that are likely to fail under safe mode.

How to solve this? Well, sadly there is no real fix to it: you either convince your system adninistrator to disable safe mode, get them to add what you want to the list of safe mode exceptions, or just rewrite your code to work around the problem. The latter is not really recommended, because it invariably involves dirty hacks that may end up being disabled in future versions of PHP or in future edits of the php.ini file by your administrator once they find out you’ve worked your way around their wishes.

15- "Fatal error: Call to a member function on a non-object" or "Notice: Trying to get property of non-object"

Both of these errors are caused by you treating a non-object variable - such as a string, an integer, or an array - as if it were an object. For example:

$foo = 1;
    echo $foo->value;

While that code might work if $foo was an object that had a property called value, it is just a normal variable holding a number and so the error pops up. However, things are rarely that easy: if you assign a number directly to a variable, you’d be pretty crazy to then treat that variable as an object!

A more common scenario is when you expect a function to return an object, but it instead returns another type of variable, and you don’t do any error checking. For example, running a query in PEAR::DB returns an object if the query was selecting data, but a simple value if you are inserting data. Similarly, calling simplexml_load_file() on a file that doesn't exist won't return a SimpleXML object with no nodes in. Instead, it will return a boolean value of false, which is clearly not an object and so will react badly to being used as such.

These kinds of problems are usually very to find, and even easier to solve: use some error checking!

16- Warning: session_start() [function.session-start]: open(/tmp\foobarbaz, O_RDWR) failed: No such file or directory (2)

This error is usually caused by the directive "session.save_path" being incorrectly set in our php.ini file. By default, session.save_path is set to /tmp, which should work fine for most Unix systems. On Windows, however, there is no directory /tmp by default, so you need to change this.

The easiest thing to do is to create a directory in your PHP installation directory called "sessiondata", then change your php.ini file so that session.save_path points to it, e.g.:

session.save_path = "c:/php/sessiondata"

If you still have problems, it is possible that the session directory has restrictive permissions on it - check the permissions on the folder, and make sure it is world readable and world writeable so that your PHP scripts can use it wherever they may be called from.

17- Notice: A session had already been started - ignoring session_start()

This error is self-explanatory - you have one session already started, and you tried to start another. However, there is a particularly situation where you may only be able to count one session_start() call, which is where people get confused. There is a directive in the php.ini file called session.auto_start, that when enabled will implicitly call session_start(). If your server has this setting enabled and you do not realise this, the chances are you will unknowingly call session_start() yourself and receive the above error.

If you have session.auto_start enabled (look for it in the output of phpinfo() ), simply stop calling session_start() yourself.

18- Warning: mail(): "sendmail_from" not set in php.ini or custom "From:" header missing

This one is fairly easy to clear up: open your php.ini file, and set the sendmail_from value to something good for a default for your site. Alternatively, add an extra parameter to your call to mail() that supplies the From header. This has already been discussed elsewhere: please go back and check the Networks chapter for more information.

19- Fatal error: Function name must be a string

This error usually rears its ugly head when you are using variable functions. If you use a variable function and the variable you are using is unset, this error will result - I often get this when I am typing faster than I can think and I accidentally hit $ before a function name. PHP naturally interprets this is a variable-function call, and tries to look up the function name inside the variable.

20- My script is doing something crazy!

If you are finding your scripts doing something particularly weird, the chances are it’s a particularly silly coding error. The most popular example of this is mixing up include files for PEAR classes. For example, if you want to use PEAR::Mail you would include Mail.php. However, if you already created (and forget about) your own Mail.php in the same directory as the other script, PHP would include that original script instead of PEAR::Mail, leading to all sorts of mix-ups.

If you fall into this trap, relax - it happens to all of us!

21- And finally, the most common error...

Whether it is due to making a typo, a slip of the mind (often less delicately referred to as a "brain fart"), or just lack of understanding, the following code has been written numerous times:

if ($foo = 3) {
    
// $foo is equal to 3, so do stuff here
}

Of course, the author meant to use two equals signs there, as the current code assigns 3 to $foo rather than comparing 3 and $foo. Such a small error as this can generate huge headaches for programmers irrespective of their experience, so do not feel bad if you fall into this trap. Many people try to work around the problem by reversing their if statements when possible, like this:

if (3 == $foo) {
    
// $foo is equal to 3, so do stuff here
}

It does exactly the same comparison, except that if they accidentally type one equals rather than two, PHP will issue an error rather than letting the mistake slide. The reason for this is because you cannot assign the value of $foo to the number 3 - 3 is always 3 no matter what. This is a safe route to take, however it obviously does not work when you have variables on both sides!

Please help me I am handicapped and support myself

Donate With PayPal

 

Donate Bitcoin

Please donate and help the handicapped.

19DQT9KTHabkJ7dUCHpzdg5XdSA5mFkCyJ



name:Arlinda Date:08.13.22 @ 23:31pm IP:1852431..79.
Thanks you are awesome. Working out good for me. I sent you 48 cents.


name:Sergio Date:08.13.22 @ 23:00pm IP:51..7241983.
Thanks you are awesome I sent you 6 cents.


name:Teddy Date:08.7.22 @ 06:06am IP:804.71..211319
Thanks I love you I sent you 58 cents.


name:Marcelene Date:08.7.22 @ 06:06am IP:81143.0.71.219
Thanks you are cool I sent you 7 cents.


name:Freddy Date:08.7.22 @ 06:05am IP:1148.70.19312.
Worked out great for me I sent you 29 cents.


name:Doloris Date:08.3.22 @ 05:31am IP:11618.51.969.
Thanks for sharing.


name:Yuette Date:08.3.22 @ 05:08am IP:191.519.6.861
Thanks you are awesome I sent you 6 cents.


name:Mark Date:08.3.22 @ 02:29am IP:182122...53029
A great help thanks I sent you 35 cents.


name:Shantelle Date:08.3.22 @ 02:09am IP:56.6.20.8204
Thanks!


name:Gina Date:08.3.22 @ 01:37am IP:41.01.81253.111
Thanks for sharing.


name:Abbie Date:08.2.22 @ 23:36pm IP:1.9.8173452.
Thanks for sharing.


name:Page Date:08.2.22 @ 23:11pm IP:31725..1.948
Thank you you are the best. Works like a charm. I sent you 22 cents.


name:Brandon Date:08.2.22 @ 18:26pm IP:51.1199861.6.
Thanks for sharing.


name:Paul Date:08.2.22 @ 17:59pm IP:..518919611.6
Thanks you are awesome I sent you 6 cents.


name:Tosha Date:01.27.22 @ 20:17pm IP:.84824.1.191
Tyvm.



Name:
Click Here to Reload

My websites do not use cookies or any google spyware.

 

Quick Support: Make it short.
Email:

Message: