Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
 
  HOME    TRACKER    PHP




Best Coding Practice


let me say that this question is a rather general programming
question, but the context is PHP, so I figured this group would have
the most relevant insight.

Anyways, this is also more of an opinion based question than one
seeking a definite answer. Recently, while maintaining a rather large
system. I needed to add an array class member to an object. It was
exactly the same as another class member, except that one array stored
regular products, and the other stored free promotional products. As
such, I needed a way to add products to the new, free array. Since all
the logic was the same between the two arrays aside from the price, I
had a few different options to do this. I'm interested in polling
which way some of the group members feel would have been the best.
Naturally these are abbreviated versions of what I envisioned as
possible solutions.
#1.
public function addArrayA($object){
//logic
$a[] = $object;
}

public function addArrayB($object){
//same logic
$b[] = $object;
}

#2. (These next two are arranged as such, because the class using
these functions is included in many script files,
all of which I may not be aware of, so there would have to be some
default value for the array that was always used
before this new array was needed)
public function addArray($object, $free = NULL){
//logic
if(!$free){
$a[] = $object;
}else{
$b[] = $object;
}
}

or

#3
public function addArray($object, $arr = "a"){
//logic
$$arr[] = $object;
}

I ended up going with option number 1, because I felt that despite the
inefficient, redundant code it would later be more readable to other
programmers that might work on the project. Additionally, I didn't
feel wholly comfortable with default variables being the only
difference between a full price product and a free product. Thoughts?




View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread
Is This Bad Coding Practice?
After recently coming back to php after working in asp for several
years, I want to do things well, so I'm very concerned with learning
good coding practices.

Also I'm trying to seperate logic from presentation as much as I can
through the use of the <?=$variable_output_goes_here?> output. I'll
give you an example.

Instead of putting the body of a for loop (that displays info from an
array in a table), in the html, I'll declare a variable and put
everything in the variable.

<?php

$display_results = '<table>'

for ($i = 0; $i < 3; $i++) {
$display_results .= '<tr><td>' . $info[$i][0] . '</td><td>' .
$info[$i][1] . '</td><td>' . $info[$i][2] . '</td></tr>'
}

$display_results .= '</table>'

?>

Then I'll output into the html like so . . .

<?=$display_results?>

My question is, even though this seems to work, now I'm learning on a
small scale at home. If I take this sort of coding habit to a
production enviornment, is it going to slow down my code if I need to
scale something up? If I'm this interested in logic/presentation
seperation, would I just be better off using smarty?

Language File, Best Practice
I would like to add international support for my site to allow some of
my users to translate the site if they really feel the urge to do it.

I don't use any CMS, the site was developed, (and refined :)), by me.
But I see that various CMSs handle languages very differently.
Joomla! for example has a smallish define file that has all the
translations.
Wordress on the other hand seems to have a function __(...) that is
altogether a lot more complicated but also more flexible.

But I am not sure that the Joomela! approach is the best, defining what
could become a rather big language file seems a bit silly to me, (well
in my case it seems to be). And there does not seem to be any naming
convention of all those defines, that could spell<sictrouble.

So, what is the best way, so far, of handling languages?

Web Surveys: Common Practice
I am just wondering, what is the current best
common practice for online surveys:

1. allowing users to vote any number of times
2. allowing one vote per IP
3. requiring email address verification (seems overly complex for a survey)
4. setting a cookie on the web browser and allowing no more voting until
the user closes the web browser
5, other

Best Practice Global Variables

I'm coming from java and coldfusion, where one can set a "global" variable
in one place (the servletcontext in java, Application.cfm in coldfusion) and
all files in that site can then take advantage of these variables without
the need to "include" a variables page in every page on the site.
Is there something comparable in php, like an Application.php or some such
thing?

One more question that's basically an extension of the first. in
development, my site is http://localhost/mysite, but in the hosting
environment, it's http://mysite

Now, let's say I have a "header" include that includes images in it, and
that header is included in multiple directory trees, so relative pathing of
those images isn't possible. Is there a preferred way in php for dealing
with this kind of thing, since i can't simply use /images/myimage.jpg since
that path isn't valid in the local environment?

Thanks for any answers. I'm doing some emergency work on a php site as a
favor to a friend and am quite out of my element.

Break In Loops A Good Practice
I have come across a While loop that my best solution seems to be to use a Break. And as I have never used a break command from within a loop I was wondering if it is an acceptable practice in PHP.

Best Practice For Making Large Queries In A Page
I've been doing php for a while now was always run into the problem of creating messy queries in my php files.

For example, sometimes I add a LEFT JOIN, sometimes I add a WHERE CLAUSE and sometimes there's a search on my page so I have to add the LIKE '%xxx%'. Basically, I want to have a organized method of generating queries. I think C# uses a mysql function like APPEND.

Should I put all my query parameters in the SESSION variables? and then just append/delete from the session variables before generating the query?

Eg.
$_SESSION['tables']
$_SESSION[where_params]
$_SESSION[like_params]
$_SESSION[left_joins]

Then before each query, I just explode the array and make my query? IS this the best solution? or is there already one out there?

Best Practice In Placing Db Connection File/folder
The site is PHP and uses MySQL.

When the database connection file is placed on the server is it better to place the db connection file or the connection folder at the root level.

In other words is it better to have the folders Connection and public_html at the same level?

Or to move the connection FILE up one level so the connection FILE and public_html FOLDER at the same level?

It makes life easier if the folders connection & public_html are on the same level because it means files can be uploaded without having to alter the
code that calls the connection file.

What it comes down to is if both approaches are equally secure or does one approach offer added protection over the other.

Best/commont Practice Orgainzing Users. Db For Each Or Id In Table??
I am not sure what the most effective way to organize a db for users
is. I have 40 users (teachers) and 20 tables (grades, assignments,
students, etc). Each needs access to its OWN grades, assignemnts, etc.

NOW I am not sure how to orgainize users in the DB. Right now I have
the code for 1 user and need to adapt it to several users.

1. A user id in each table and the same db for all users.?

OR

2. A different db with its own set of tables (same names) for each
user.?

Option 1. would be easier for me because it would only involve adding
an id to a the connection string in the include. Option 2, would
require modifying query strings throughout the code in the
application.

However I heard that ISPs usually limit the number of dbases per Mysql
server (don't know why). On the other hand the dbase per user approach seems to me more efficient since the number of records in a table is greatly reduced
and each user has access only to its own db.

What is best/common practice in this situation having in mind that the
number of users is limited to around 40 if that makes any diffrence at
all.

Database Connections To Fetch Data, Best Practice?
I have many classes that use database connections to fetch data and manipulate on it. I also have database abstraction class that is handling all the database queries and so forth. Usually all my classes take instantiated database object as the first parameter to constructor so they know what database to use: ...

Pre-coding
I need some advice on feasability etc on using PHP (MySQL backend) for a little project that I have in my mind. I'm new to PHP, but not programming (thank God!) - so barring syntax, logic should be fine (I hope), but I'm unsure if PHP has the ability to do what I need (told you I was a newbie eh?? )

The project ....
Simply put, the idea is for a series of drop down boxes to kinda act as a "filter"for data in the records in a mysql db. Ie, lets say for example that my db contains info about cars, with the columns, Make, Model, CC, Colour etc etc.

Initially the user would see (in the above example), 4 drop down boxes, each with data pulled from the db relevant to their column id. The pulling of data I dont have a problem with - thats sorted. However, in the brief coding exercises I've done, its the ability to have a user choose any of the four drop boxes, and all the other 3 dropdown boxes data be ammended ? Am I explaining this well ?

Lets say that I choose 'Red' from the Colour drop down - then the drop down box for Make should change to only be Makes where colour = red, Model should also change to where colour = red etc etc etc ? With me here ?

At any point the user will have the ability to 'go' their selection - and all the records are displayed for the user. Am I wanting too much here from PHP? I've been told JScript would do what I need (better than PHP?????) but frankly I dont have the time to start learning another lang, so if this can be done in PHP I'd be happy.

Best FTP Client For Coding PHP
I currently use Eclipse for creating the PHP application, which is
great for editing but quite slow when using FTP. But when im testing i
like to use CuteFTP Pro for quicky editing and seeing the results. Im
getting fed up with CuteFTP as its really flakey.

I am looking for a simiar application like CuteFTP that has an inbuilt
editor but can not find one, every one I have looked at uses a
different application to edit.

Can anyone recomend a FTP editor that works well with quickly editing
PHP web applications?

Coding Methods
Im trying to figure out some better coding methods. Maybe you more experienced guys can help me. Right now im working on a new site which is a bit larger than i usually do. Currently i have a main Index.php file which has functions which call functions that display html (footer.php, header.php, main_table.php). And inside these include files, i have php code which call him mysql functions, etc, etc.

But after looking at for awhile, i can see some forseeable problems. What are some good coding methods that can help me code better and make it easy for me to update the code with out having to rewite everything.

Bad PHP Coding Practices?
I'm just wondering what are some bad (inefficient / resource intensive) PHP coding practices. For example, in Visual Basic string concatenation in a loop can really slow things down since a new string is created each time. Object creation has overhead and only so many objects can be created before it bogs down. Any significant problems with $a .= $a + "text" or objects in PHP? Any other bottlenecks?

Removing PHP Coding
I have php coding that is stored in mysql blobs. Now I want to index words in these blobs in an attempt to make some sort of a search engine. Example: How can I use php to make this mysql text:

"Once upon a time there were <?php echo $num_bears ?> bears in a small cage in a zoo in Russia. They had <?php echo $num_relatives ?> relatives that lived there with them."

Change into this: "Once upon a time there were bears in a small cage in a zoo in Russia. They had relatives that lived there with them."

Point is: - remove everything between and including "<?php" and "?>" I'm trying to do some indexing, and I need to remove all my php coding... :)

Coding Convention
Consider the following code (contained in a class method):

switch($sectionType)
{
case 'layout':
return $this->getLayoutSection($sectionName);
break;
case 'content':
return $this->getContentSection($sectionName);
break;
}

Obviously neither break is going to get execute, because the method will
return before it gets to them.

I have gotten into the habit of putting breaks at the end of every case in a
switch, even if it is not necessary (as the above). I have it somewhere in
the back of my head that this is the "proper" way to do things. But now
that I think about it, I have to ask, is this true? Is it consider good
practice to always end case statements with a break, even when not
necessary?

Anyone Use UltraDev For Php Coding?
I'm considering using Dreamweaver for general web design and have seen that UltraDev can be extended to use php. Has anyone had experience of this and if so, what are the good/bad features of this? In particular, I would want to create code that accesses a mysql database. I currently do all this by hand.

Standard Coding...
I was wondering if there is a standard when mixing PHP and HTML script on a
page... and if there were any articles on this subject...

i.e. do I make every page a .php page on my website and echo html when I
need to or...

should I make every page html and embed php when I need to..

Obviously this only applies to pages where a mixture of php and html is
required...

for example... which is better or more standard....

<html>
<head>
<title>title text</title>
</head>
<body>
You name is <?php $name?>
</body>
</html>

saved as index.html

or

<?php
echo '<html>'
echo '<head>'
echo '<title>title text</title>'
echo '</head>'
echo '<body>'
echo 'Your name is '.$name;
echo '</body>'
echo '</html>'
?>

saved as index.php

Coding Style...
When i write a script, i tend to seperate the differnt functions with differnt files. For example. When i creat a user management script, i create and add_user.php file and a modify_user.php file, and so on. I also see a lot of people who simply write one big 10 meg php file that includes everything in one. (seperated into functions.)

Is there an advantage to this? Or is it just a matter of personal prefrence? I guess it really doesnt matter that much, i just wanted to know.

Streamline PHP Coding
This script was build to take a ZIP file that has been uploaded to our server, extract the TXT files within (which are always the same) and INSERT the contents of those TXT files into a MySQL DB that we have setup. Is there a way to stream line this coding and help it run faster? One of the TXT files in the ZIP has over 600,000 records and takes nearly two minutes to INSERT into the DB. Code:

Coding Standards For PHP
I've picked up much of my PHP coding from various tutorials scattered about the web. I'm proficient in my coding but believe that my method isn't up to conding standards. Can you refer me to sites which use good coding methods/standards? Or is there a good reference site (other than php.net)?

Coding XHTML
I was wondering what the correct way to integrate xhtml into php? Do you design you your entire site with the xhtml inside of php or only embed the xhtml in php when necessary? For instance would you put your entire xhtml output and php with in a variable and echo it out all at once.  Or does it really depend on the situation?

Highlight_string Coding Problem
Here's my goal. There's a textarea box, where I type text. I created a ubb code, [table] where it shows a brown table. This is where I'll have my PHP code. My goal is, the text between the [table] and [/table], I want the text to be in a highlight_string() function.

Simple Wiki As PHP Coding Example?
I'm currently learning PHP using the ORA "cuckoo" book. I'm looking for
some reasonably interesting sample code to read and thought that a
*simple* Wiki could be ideal. Can anyone recommend a Wiki which
implements the basic functionality only to keep things simple, written
in nice clear PHP code? I'm hoping that a couple of hundred lines or
less of PHP will suffice to get a basic wiki running, without resorting
to obfusticated coding contest tactics...

Coding Standards Without Control?
A recent poll asked if programming standards are used by development
organisations... and if they are controlled.

None: 20%
Yes, but without control: 49%
Yes, with control: 31%

Participants: 369

A majority of the participating organisations have coding standards...
and a majority does not control them ;o) What is the situation at your
location?

Want Php Coding/script For Timing
Any one know about coding/script which can show the different between two time for example the orignal time is 2:00PM and the current time is 2:30PM so the result will be 30 mintues...

Coding/form Problem
I am just in the very early stages of learning Php and just need..

I have a form which includes values. However when I test it, the
values are not added up and carried to the results page. I just
wondered if you can spot whats wrong with it?

This is the form on the page tourprice.php:

<form name="frm_tourprice" id="frm_tourprice" method="post"
action="tourprice_processor.php">
<table width="60%" border="0" cellspacing="0" cellpadding="3">
<tr>
<td>Number of Adults </td>
<td><input name="numAdults" type="text" id="numAdults"
/></td>
</tr>
<tr>
<td>Number of Children </td>
<td><input name="numChildren" type="text" id="numChildren"
/></td>
</tr>
<tr>
<td>Tour Name </td>
<td><select name="tourName" id="tourName">
<option value="500">Highlights of Argentina</option>
<option value="700">Highlights of Western Canada</option>
<option value="900">Egyptian Pyramids and More</option>
</select></td>
</tr>
<tr>
<td>&nbsp;</td>
<td><input type="submit" name="Submit" value="Submit"
/></td>
</tr>
</table>
</form>

On the tourprice_calculator.php page it is supposed to add everything
up depending on what you select and give you the correct cost. I keep
getting a zero returned though.

This is at the top of tourprice_calculator.php

<?php
$numAdult = $_POST['numAdults'];
$numChild = $_POST['numChildren'];
$basePrice = $_POST['tourName'];
$tourPrice = (numAdult * basePrice) + (numChild * basePrice)
?>

Further down on the page I have the following:

Tour Price Calculator </h1>
<p>The estimated cost of your tour is <strong><?php echo
$tourPrice; ?></strong>.</p>
<p>Price includes hotel, accommodation, and travel expenses during
the tour. They do not include airfare to the starting destination.</p>
<p><a href="tourprice.php">Calculate</a> another tour.</p>
<p><a href="contact.php">Contact</a> one of our qualified
agents.</p>

Did I Get My SESSION Variable Coding Right?
Here is the code that i've written:

<snip>

Made an image so it's easier to read.

When I visit my page it seems to set the SESSION variable every time. Even when I visit the page without sending a querystring and the SESSION variable is already set.. What have I done wrong in my code?

//set SESSION colour variable.
If I've passed a "querystring" to change the colours then change SESSION colour.

//extract SESSION colour variable.
If SESSION variable exists then extract it otherwise choose to set SESSION variable to orange.

//setup PAGE colors.
Use SESSION variable to setup my page colours.

Color Coding PHP In HTML
I'm really just looking for a script, but I'm having a lot of trouble finding one. Maybe I'm using the wrong "Key" "Words", I dunno. I need a script that will color code PHP and maybe even JavaScript much like these forums do. Any ideas on where I can find such a thing?

Optimization In Coding Style
I was wondering is there a point in optimization in code style... I
have used to put parenthesis around some php keywords, but they are not
needed.

For example, I always use:
echo( "String..." );
but I could use
echo "String...";

the same thing is with return:
return( $tempHTML );
as opposed to
return $tempHTML;

Also is there a point to variate between string delimiters " and ' ?
ie. is it better to use single quotes instead of double quotes if I
don't won't any variable in a string? For example:
'This is a string...'
as opposed to
"This is a string...".

Double quotes are needed, of course in other cases:
"Frankly my dear, your name is ${nameOfTheUser}!"

I know it sounds stupid, even hard to read, but what are your opinions?

Coding For PHP Cookie Setting...
I want to submit a form to it's self and then set a cookie with the sent variables from the form. Then I want to call this cookie to set the variables in the submit form next time it is visited, so they don't have to keep typing it in ever time they visit. ie-
Code:

Am I Too Wired? On Coding Style
I have a question that spining around my head for a long time. I
prefer to make this kind of if statement:

if (!$GLOBALS['phpgw_info']['user']['admin']) Header(
'Location: '.$GLOBALS['phpgw']->
link('/', 'menuaction=forum.uiforum.index')
);

But almost all the 'good' php code I saw write it this way:

if (!$GLOBALS['phpgw_info']['user']['admin'])
{
Header(
'Location: '.$GLOBALS['phpgw']->
link('/', 'menuaction=forum.uiforum.index')
);
}

the argument is the latter is more readable and easy to understand. But,
to me, a if statement immediately followed by another statement or
function call is more readable and easy to understand. It saved me from
thinking what's after this statement or function call. Truly, I think
keeping a stack of 'if' or 'for' in the brain is difficult for me, I
tends to remove the {} and add the statement after if-clause when if
statement contain only one statement.

I am just thinking if my way of keeping code logic in brain is too
wired. If most people truly consider the {} more easier to
read/understand, I'll force myself write understandable code; if there
are only very small difference in understanding (considering reading
10000 line of source, even small difficulty counts), I would like to
keep my style.

Coding A Site Search...
I am starting a rather large content based site. I need a search for my site that will handle multiple words, etc. that I can have search a certain field in my db (mySQL). Are there any good places to learn how to do this so it is very efficient and speedy or are there any scripts that already do this that you could recommend with minimal modifications?

Includes Or Embedded Coding?
i am a programmer but i have never coded in PHP. I am building a PHP based site with thousands of pages through a friend who claims to be proficient in PHP.

Anyway, he is suggesting that we embed PHP code within the HTML files but I have heard that it is better to keep HTML and PHP functions separate.

Please advise which method is better for coding and any input you guys can give will be great. We just want to be build an efficient site that we can easily update the design and code.

Database/coding Issue?
I have users table. with usernames and info on those users. The info that i have setup for this portion is userid_2 What i have planned for this is to call up that userid_2 from everyuser in a sequence. like this:

user1: userid_2 = 1
user2: userid_2 = 2
user3: userid_3 = 3

now i would like it to basically record all of these numbers.. (not add them.. subtract.. nothin like that) just record them. Then in the .php file. I want to have an if statement saying that:

if userid_2 = 1
echo user1's information

then display an image.

if userid_2 = 2
echo user2's information

then display a different image i currently don't have anything coded. on account of that i would like your guys help. b4 i totally screw it up.. then get lost. and having to rewrite it all again. (i know thats how most people start out.) but thats the miracle of these forums.

Ratings Query Coding?
I am trying to intergrate a ratings system into my project, the problem I have is I can not find an average ratings, I will try to explain clearly below with coding examples
 
OK I have 3 recordsets 1 for restaurants with various different buildsql (primary key dine_id) I now am trying to intergrate a ratings system with this project

so I have 2 additional recordsets in the code below the queries already relate to the right outlet because the code below is within my repeat region Code:

Coding Tip To Prevent Comparisons Becoming Assignments
This is a simple coding tip I learned to prevent comparisons from becoming
assignments (and this becoming a hair-pulling session during debugging):

in comparisons, try to put your constants on the left hand side of the
operator and variables on the right hand side.
example
if (3==$x) {
//do something
}

if ($x=3) {
//do something
}
if this were intended as a comparison, it would never be flagged as an error
by the interpreter or compiler (in PHP's case, interpreter).
With this line, I missed an = and the interpreter won't complain. it simply
assigns 3 to $x and does something every time. With the top line, you can
fix your code quickly because of the error message generated if you miss an
=.
Consider it a good coding habit? Then again there are books on this (if
they are still published).

Coding Styles: Defines Vs. Variables
I'm interested in knowing what you PHP coders prefer to use in scripts that use some sort of configuration include file -- whether or not you use define("NAME","VALUE") or if you just set regular variables ($var) to contain info.

I'm going to try to lean more towads using the 'define' method myself, since it seems that variables could easily be hijacked via the query string (in theory)... However, I'd like to see what other people have to say about this. If you've got an opinion on this topic, please don't hesitate to share it.

Creating A Coding For Greeting Cards.
I want to run a php script that call virtual greeting card. How to do that?

General Good Coding Practise
Although I have no specific problems, I would like some insight into good coding in PHP,
Things like, when you are printing alot of HTML with PHP code in the middle what is the best/effecient way: PHP Code:

Trade PHP Coding For Design Work
as a server-side veteran but fledgling front end designer, i would be
interested in doing a little PHP coding in exchange for layout and
design

anyone out there interested in such an exchange?

i figure, an hour for an hour. that sort of thing.
-------------------------------------------------------------------------------

Form With Captcha Security Coding
I've been trying to add a captcha script to a form, having it check the security image first of course, then email the contents of the form. It checks the image,  goes on and says "thank you, your message is......etc", but I can't get it to send the email.....if anyone can look thru it and see what I'm doing wrong. Code:

Disable Coding In Textboxes/Textfields
Is there a way to disable PHP, HTML, and the sort in textboxes and input fields? There are things called SQL Injections which are usually used in an url or input field to steal data from the database.

Coding A Form From Email Submission
I have a customer who wants his contact page customized to be a form with questions to be answered by the person trying to contact him. When they are done filling in the form it is suppose to be emailed to him. I can not get this form to work right. Code:

Basics About PHP Syntax, Structure And Coding Standards?
Can someone direct me to the best place on the web to get the basics
about PHP syntax, structure and coding standards? I need to see a
comprehensive list of all commands, data types, key words, etc.

I am an experience programmer but very new to PHP.


Whats The Best Language For Coding Graphs On The Internet?
Whats the best language for coding graphs on the internet?

Coding For Save HTML File In Folder?
my quesion:

1. how coding for save HTML file (website build use template like us build one blog use blogger.com) in different folder for any user?
2. how coding to make template so used by any user?
3. how coding drag and drop and then save that drag and drop?

PHP And MySQL A Faster Option Than Coding HTML Files?
In the article about driving your website using PHP and MySQL it seams that if you have large amounts of information ten it would take ages to actually input data. Does sitepoint use a different type of databse or take a shortcut.

Is PHP and MySQL a faster option than coding HTML files. I mean by this, will the page load slower or faster. How about if you use multiple SSI on a HTML page. Would the PHP and MySQL solution be a faster loading one.

Coding To Detect Number Of Students That Evaluating A Person
i really in need of a php script that can ensure SYSTEM able to trace the number of people that log in into the system and evaluating person A and detect that number so that we will know whether person A has been evaluated by all her students?. This is to restrict the number of people evaluating a single person to the exact number of students only.

eg: person A teaches 10 students and when all her students evaluate her teaching, the system actually detects the number of student under her that already evaluate her; and if the number exceed, the system will detect 'has exceed the number of students'.

what if there are person A till Z? while, the number of students for each person is different?

My problem is, is there is a php code to detect the number of people that evaluating the same person (indicate as A) and already fill the quota for evaluating that person?

Coding "init" Function For An Extension...
Another question about writing PHP 5 extensions. What's the difference in
PHP_MINIT() / PHP_MSHUTDOWN() and PHP_RINIT() / PHP_RSHUTDOWN()? When would
a "per request" init be made?


Copyright © 2005-08 www.BigResource.com, All rights reserved