FRIHOST FORUMS SEARCH FAQ TOS BLOGS COMPETITIONS
You are invited to Log in or Register a free Frihost Account!


How To : Improve Your PHP Programming






Did this help you at all ?
Yes, Definately.
87%
 87%  [ 21 ]
No, It Did Not.
12%
 12%  [ 3 ]
Total Votes : 24

izcool
Hello everyone,

I've decided that I would make a thread here describing the different things that I do to improve other people's PHP scripts.

Hope you enjoy it and learn a thing or two.

1 - Your PHP Tags
I know some of you prefer to use the short tags when writing PHP scripts <? ?> but this is not always the best way of doing it.
The standard tags <?php ?> are much better as they will work on every server that you write your PHP code on. You may move to a server some day that doesn't allow the short tags or the ASP-style tags and you will have to sit for an hour and update your PHP scripts.

2 - Debugging Your PHP Code
Some of us may run into a problem when programming a PHP script and don't know what's wrong with it. The error_reporting() function in PHP helps you out by telling every error you have on your page. To show all of the errors on the page that you're editing, put this on the second line :

Code:

error_reporting(E_ALL);


3 - Debugging Your PHP Code (again)
When you finish editing your 1200-line PHP script, click onto it in your Internet browser, you see an error that says that is on line 561. Don't hit the panic-attack button quite yet, because there is an easy way to find out what line 561 is. Follow these easy steps :
- Open up Microsoft Notepad
- Paste your PHP script into it
- Go to 'Edit' >> 'Go To...' (or Control+G)
- Type in line #561 and hit the enter key
- Your cursor is taken to line #561.
- Look above and below line #561 to see if there is any kind of trouble.
- Fix the error, re-upload the script to your website, and most likely it will work. If there is another error, repeat the above steps.

4 - Using Comments
If you have a 1200-line PHP script, it may be quite hard to figure out what's going on all through-out it. The solution to figure out what you're doing is to add PHP-comments.
PHP-comments are different than the <!-- HTML Comments --> as they are not outputted to the user's page (meaning that they are not even going to see it in the source code).
There are three ways to make comments in PHP :

Code:
 
<?php
// The double-backslash is my personal favorite.  I add another set after my code so that it looks even, though it is not necessary. //
# The hash-style comment is another way of making a comment.
/* And, this is the final way of making PHP-comments.  You can use
multiple
lines
at a time by using this style. */
?>


You can decorate it however you like, you are the only one who may use them.

5 - Indenting Your PHP Codes
I don't personally like to indent my PHP codes, but it helps when reading it. When I do have to, I use the tab key to accomplish this. Example :

Code:

<?php
// Settings //
    $var1 = "This";

// Showing Variables //
    if($var1 == "This"){
        echo"You said This";
    }else{
        echo"You said That";
    }
?>


6 - Improving your PHP-File Includes
I'm sure that most of us on here include a PHP file or two for our layouts. Well, what if your layout file was missing ? Wouldn't that look pretty unprofessional to the people on your website ?
In every PHP-script that I write, I make sure that the file exists before it is even included. Here's an example :

Code:

<?php
if(!file_exists("layout.inc.php")){exit("Error :  LayOut File Missing");}else{include_once("layout.inc.php");}
?>


I'm sure that a small error message will seem better than half a page that is all messed-up looking.

7 - Your MySQL Queries
Sometimes when you're writing a PHP script that includes connections to your MySQL database, you may run into a few problems. Most everyone that had MySQL problems ran a command like this one :

Code:

<?php
mysql_query("INSERT INTO tableName ('id','name') VALUES('1','Mike')");
?>


..and they figure out that it's not inserting into their database. Here's the solution to this :

Code:

<?php
mysql_query("INSERT INTO tableName ('id','name') VALUES('1','Mike')") or exit("MySQL Error :  " . mysql_error());
?>


8 - Combining Alike If-Then Statements
You may have a register page, and want to make sure that everything has been filled-in. You may use many if-then statements like so :

Code:

<?php
if(!$_POST[name]){exit("Sorry, but you did not fill-in all of the requested fields.");}
if(!$_POST[email]){exit("Sorry, but you did not fill-in all of the requested fields.");}
?>


You can combine these two lines into one by joining their if-then statements together :

Code:

<?php
if((!$_POST[name]) || (!$_POST[email])){exit("Sorry, but you did not fill-in all of the requested fields.");}
?>


Simply, || is the same thing as OR and && is the same as AND.

9 - Using echo or print ?
Most of you may say 'echo is the same thing as print', in which I agree with you all. The echo command is much faster than the print command, and is one less character to type. The echo command came later than the print command (I believe), so you make the judement on which to use.

10 - Printing out a Huge Chunk of HTML at a Time
Well, I'm sure that many of us found a way to get around this, but I'd like to share with you a few of the ways you can do it.

1 - Break off your PHP-code, print the HTML, and start your PHP-code up again. (I don't prefer doing this as it looks pretty unprofessional to me).
2 - Adding backslashes to each HTML tag. (It works, but takes forever to do).
3 - Using the echo/print command, but without having to do much work. (I recommend) :

Code:

<?php
// Showing a huge chunk of HTML at a time //
echo<<<END
<font face="Verdana" color="Orange" size="3">Large, Orange Text in Font Size 3</font>
<br><br>
More HTML down here..
<br><br>
<div align="Center">Centered text</div>
END;
?>


11 - Multiple Items in the If-Then Statement
As said in #8, you can combine alike if-then statements into one. This also works...

Code:

if($this == "that" && $that == "this"){echo"This and that match";}


But from experience, it is best to assign seperate brackets () around them as it does not confuse the code...

Code:

if(($this == "that") && ($that == "this")){echo"This and that match";}


12 - Saving Time with Varibles
When using functions, and you want to include a load of settings, you need to include every single of them at a time, as so...

Code:

<?php
$time = date("Y-m-d:H.i.s");
$name = "Mike";
$comment = "Just a simple comment";
function show(){
global $time,$name,$comment;
echo"$time - $name - $comment";
}
show();
?>


..But you can save your time by including only one variable instead of three, as so...

Code:

<?php
$_SETTINGS[time] = date("Y-m-d:H.i.s");
$_SETTINGS[name] = "Mike";
$_SETTINGS[comment] = "Just a simple comment";
function show(){
global $_SETTINGS;
echo"$_SETTINGS[time] - $_SETTINGS[name] - $_SETTINGS[comment]";
}
show();
?>


..Even though you'll spend a little more time by typing $_SETTINGS[] or just by copying and pasting it.

13 - Shortening exit(); and die(); Functions
If you want to stop the page load, you can use the exit(); or die(); functions. But, if this is all you want to do, then you can shorten it...

Code:

exit();
exit;

die();
die;


14 - More Usage of exit; and die;
If you want to stop the page load and show text, you can do this..

Code:

echo"You did not finish all of the required fields.";
exit;


...Or...

Code:

exit("You did not finish all of the required fields.");


15 - Using arrays to Store Data
Arrays are used to store temporary data in a PHP code. Here's an example...

Code:

<?php
$names = array("Mike","Charlie","Amanda","Caroline");
echo $names[0]; // Outputs 'Mike'
echo $names[1]; // Outputs 'Charlie'
echo $names[2]; // Outputs 'Amanda'
echo $names[3]; // Outputs 'Caroline'
?>


16 - Ultimate Help Source for PHP Problems
Most people don't know about this, but there's lots of good documentation that can be helpful at PHP.net. Use the search box on the upper right to type-in your function, like echo, and it'll redirect you to a page explaining what the function is used for and examples on how to use it.

17 - Take A Break
From personal experience, I often get exhausted from sitting in front of the computer for too long, especially when I run into a trouble with PHP. Grab a soda, stretch, and try to focus your mind on something else for a few minutes and then get back to your work. Most of the time, it helps. But I'm not guaranteeing that it will work for everyone though.

18 - Making Your Pages Load Quicker
This will only work if you use MySQL DataBase connections to your website's backend. Most people leave-out the mysql_close() command, as they never heard of it or never care to put it. It really does matter, as you are leaving open queries out and not closing them. Eventually, this adds up and makes your MySQL-based site load a LOT slower.

19 - Check How Much Your Site Uses MySQL
I am a huge fan of using MySQL DataBases on websites. I used to own a big web game about a year ago that was very MySQL-reliant. I noticed that the server was lagging so much that the MySQL database it was using was overloading on account of how many queries a second the server is performing. Surprisingly, it was about 100 queries a second ! That's way too much for anything to handle, so that's a good sign to tell you that you need to either optimize your code, or move to a dedicated server. This is the code that tells you how many queries a second your MySQL-based website is using :

Code:

<?php
echo mysql_stat();
?>


This is an example of what the above code returns :

Code:

Uptime: 889955 Threads: 3 Questions: 101414520 Slow queries: 32 Opens: 2055 Flush tables: 1 Open tables: 248 Queries per second avg: 113.955


Take note of the last line of the section above. This was from my actual gaming website from about a year ago, it was fenominal on how reliant my site was on MySQL. The average users online was about 6.

20 - Optimizing and Repairing Your MySQL DataBases
I used to own a big web game, and I found out that there was a lot of "overhead" on my MySQL tables, as there were about 100 queries a second to the database (see the tip above this to check how many queries a second your MySQL site is using), and I found out that you can optimize and repair tables to lower the overhead. I ran these MySQL commands in a cron job every 10 minutes, due to the popularity of my webgame at the time. I do not recommend smaller websites to run it as much, but when you see overhead in phpMyAdmin, then that's when you should.

Optimizing :

Code:

<?php
$result = mysql_list_tables("YOURDATABASENAMEHERE") or exit("MySQL Error :  " . mysql_error());

while($row = mysql_fetch_row($result)){
echo".";
mysql_query("OPTIMIZE TABLE $row[0]") or exit("MySQL Error :  " . mysql_error());
}
echo"Optimization Done";
?>


Repairing :
Code:

<?php
$result = mysql_list_tables("YOURDATABASENAMEHERE") or exit("MySQL Error :  " . mysql_error());

while($row = mysql_fetch_row($result)){
$result1 = mysql_query("CHECK TABLE $row[0]") or exit("MySQL Error :  " . mysql_error());
$row1 = mysql_fetch_row($result1);
   
if($row1[3] != "OK"){
echo"$row[0] : $row1[3]<br>
Repairing : $row[0]<br>";
$result1 = mysql_query("REPAIR TABLE $row[0]") or exit("MySQL Error :  " . mysql_error());
echo" : Fixed<br>";
}else{
echo"$row[0] : $row1[3]<br>";
}
}
echo"Repairing Done";
?>


21 - If MySQL Still Has Problems, Consider Using Oracle
A very popular webgame similar to mine (same concept) made a huge switch a few years ago from MySQL to Oracle. I have not tried Oracle, but it did them a lot better.

I hope I've helped.

Best of luck,
- Mike.
Maxalou
Well, these are the basics. But what can you do without them? Quick tutorial, no useless Bla Bla and easy to understand. Well, i already know how to program in PHP but it's realy usefull. 5 on 5.
Daniel15
A nice tutorial, especially for beginners...

Quote:

I don't personally like to indent my PHP codes...

Try to read your code in 2 or 3 years and see how well you understand it... You should try and indent all the code you write, it's so much easier to read (especially if you have nested 'if' statements)

And the bit about debugging, the Windows 95, 98 and ME notepad doesn't have a goto line function.

Finally, maybe you should add something about using a PHP editor? Something like ConTEXT (http://context.cx) makes PHP programming so much easier.
chanchunyu
I didn't learn php step by step from the beginning....so it definitely helps me!
thanks!
A nice tutorial Very Happy
Devil
Nice Tut boss ,

but for ur 3rd comment wouldnt it be easier for people to use php editors , u get them free all over the net ,


anyway i am not in php programming yet , cuz i dint find a easy way to start . so if u people could just guide me ,where to start Razz
izcool
Devil wrote:
Nice Tut boss ,

but for ur 3rd comment wouldnt it be easier for people to use php editors , u get them free all over the net ,


anyway i am not in php programming yet , cuz i dint find a easy way to start . so if u people could just guide me ,where to start Razz


I've never used any kind of a PHP editor, so I use Notepad to debug my codes. Rolling Eyes

- Mike.
lllgrklll
try using notepad++ for php programming...

It's free, fast, light, with autocomplete feature, and my favourite, it has the option to close the brackets, I really don't know how to explain, but you can try and see. Just search google for notepad++.


As for the tutorial it's good for advance programmers too Very Happy. I have biig problems with mysql as I had to deal with huge tables. I optimized the code using EXPLAIN SELECT, SHOW VARIABLES, SHOW STATUS and SHOW PROCESSLIST.

Thanks for tutorial...
faris1981
Very Happy
thanks for the tutorial
newaira
izcool wrote:

6 - Improving your PHP-File Includes
I'm sure that most of us on here include a PHP file or two for our layouts. Well, what if your layout file was missing ? Wouldn't that look pretty unprofessional to the people on your website ?
In every PHP-script that I write, I make sure that the file exists before it is even included. Here's an example :

Code:

<?php
if(!file_exists("layout.inc.php")){exit("Error :  LayOut File Missing");}else{include_once("layout.inc.php");}
?>



Better to use:
Code:

<?php
require_once("layout.inc.php");
?>


Does the same job.
izcool
If require_once() does the same thing as include_once(), why is it better ?

- Mike.
newaira
require_once is it easier to read, understand, and maintain.

I forgot to say good job on the rest of your how to points.
budazz
nice tutorial sir i hope you could post more tutorials to help us... Laughing
rash52
well im going to save it in ma hardrive
SagMan
Thank you for this article it is really useful
Reflex
Thanks for the long tutorial about PHP,
Really needed this alot Laughing
So I voted Yes, definately Twisted Evil
taz699
it's best to use a php script editor like daves php edit. (i found to be the best)all the lines are numbered and and everthing from functions to text is color coded for easy viewing which can be changed by the user. there's alot of different editors at downloads.com. they save alot of time.
charliehk
Is it a freeware? If so, where to download? Idea
taz699
yes it's freeware and it's at http://www.downloads.com . good luck with your scripts.
Kynoo
I wanna begin creating a website, unfortunately I don't know anything... According to you, is it possible to start with PHP?
I don't wanna learn HTML lol.
BlackSkad
Aiaiai, then I recommend you to find another hobby.
HTML (or xhtml) is the core of each and every website, even those pretty ones with flash. So you will realy need it.
But it's not difficult. If it was, there wouldn't be so much webite, isn't it. It's just like driving a car: it seems difficult, but when you see how many people drive one, it's impossible to be difficult Very Happy

So, just look for some easy html-tutorials on Google and you're set.

Goodluck,
BlackSkad
pagaldivanna
thanx ......it's help me alot.....i just start my forum....and it did help me.......thanx
charliehk
taz699 wrote:
yes it's freeware and it's at http://www.downloads.com . good luck with your scripts.

www.downloads.com redirects to www.download.com, but I cannot find "daves php edit" when I search for the keywords! Question
RealX
i alredy knew some php, and now i know some more Wink
there is some useful stuff here
Dread Lord Chaos
Wow, this post was EXTREMELY useful. I'm a PHP n00b..I actually came to this site hoping to learn it and get a grasp of it and stuff like this really helps. Thanks a lot Smile
Aelita
nice tutorial, i voted yes, beacuse thats the positive choice not because it helped me... I've read tons of tutorials already and books. I still don't know a lot, but I'm getting better. I'm better at fixing other peoples problems than creating my own stuff, but anyway good job that will be very helpful to people. Now if we can just get a seperate topic for all the comments...

*edit*
Forgot the reason I even decided to reply.
HERES A GREAT SITE FOR PHP NOOBS AND EXPERTS!
http://phpfreaks.com
ENJOI
haziwkd
thanks, it's helpful for me~
i voted yes Very Happy

btw, i am a newbie of PHP
is it need to learn a lot of HTML before learning PHP?
mathiaus
Locked due to spamming Evil or Very Mad

-close-
rvec
unstickied it. Going to make a new security and PHP FAQ sticky later. This one is a bit outdated.
Related topics
E-Cards with PHP & MySQL
How To : Secure Your PHP Website
how to use php?
Your favourite book (official)
Buying a good PHP book
great asp and PHP programming software
PHP-GTK introduction
Improve PHP skills
I want to learn php.How can I
What is a good or bad php code?
Need help on PHP programming....
How competitive is PHP?
Directory tree in PHP
PHP and Javascript Issue handling data from a mysql query
This topic is locked: you cannot edit posts or make replies.    Frihost Forum Index -> Scripting -> Php and MySQL

FRIHOST HOME | FAQ | TOS | ABOUT US | CONTACT US | SITE MAP
© 2005-2011 Frihost, forums powered by phpBB.