Results 26 to 50 of 73
-
11-06-2004, 06:04 PM #26Disabled
- Join Date
- Feb 2003
- Posts
- 14
Here is an alternative for including files and checking for errors (versus checking if the file exists first)
Sample code:
PHP Code:if(!@include_once("file.inc")) { echo "There was an error including an important file."; exit(0); }
0
-
01-08-2005, 12:28 PM #27Newbie
- Join Date
- Jan 2004
- Location
- K.S.A
- Posts
- 13
giropets, nicly done but it's :
PHP Code:$_SETTINGS['time'] = date('Y-m-d:H.i.s');
$_SETTINGS['name'] = 'Mike';
$_SETTINGS['comment'] = 'Just a simple comment';
and since we came about quotes, I will add:
Using Single Quotes VS. Duoble Quotes
some poeple don't know the difference between single and double quotes..
single quotes are faster than double ones because it wont parse variables while the double quotes will look for variables to parse ..
so if you have only hardcoded text, use single quotes but if you have variables use duoble quotes..
example:
PHP Code:$var = 'value';
echo 'this is $var'; //prints "this is $var"
echo "this is $var"; //prints "this is value"
We don't need a reason to help people0
-
01-12-2005, 06:40 PM #28Temporarily Suspended
- Join Date
- Jan 2005
- Location
- California
- Posts
- 19
Thanks a bunch giro
0
-
01-12-2005, 07:26 PM #29Web Hosting Master
- Join Date
- Dec 2004
- Location
- Canada
- Posts
- 1,097
Not bad. Good pointers, though that include code is really quite unreadable, considering your point about readability later on...
Want to also point out that using globals is generally bad practice. Avoid them if you can. For things like settings, or DB pointers they're fine, but try to avoid using them for data that may change through the script's execution. They're a big pain to debug when you run into problems, and just poor design in general. Also, there's nothing there about OO.
Now, for my own points:
Curly braces are unnecessary if you only need to execute a single statement. You *need* to indent things nicely if you do this though, or it's completely unreadable (note that this applies to for, foreach and while statements as well):
PHP Code:if (!$user->loggedin)
error_message("You aren't logged in! You can't access this page.");
PHP Code:if (!$user->loggedin) error_message("You aren't logged in! You can't access this page.");
Ternary conditionals are handy too. A bit confusing at first, but handy once you learn them. They 'return' a value based on the condition given. Here's a simple example:
PHP Code:echo ($user->is_admin) ? "You're an admin!" : "You're not an admin.";
PHP Code:$params['description'] = (preg_match("/^[A-z0-9]{5,30}$/", $_POST['description'])) ? $_POST['description'] : "Default";
Oh, another thing I see a lot that really is quite pointless. Don't use an if construct where it's not required. Generally this is when returning from a function. Granted, this is much more ambiguous in a loosely typed language, but the point stands. Example:
PHP Code:if ($user->loggedin && $user->is_admin) return true;
else return false;
PHP Code:return ($user->loggedin && $user->is_admin);
That's all I've got for now.0
-
01-12-2005, 08:49 PM #30Web Hosting Master
- Join Date
- Dec 2004
- Location
- Canada
- Posts
- 1,097
Well, since the end of my post was about SQL, it's time to rant about database design. It's not really 'PHP programming' as the title suggests, but beginners almost always are interested in using the two together. Other data storage methods are clumsy and much more difficult to implement.
So, without further ado, my attempt at explaining database normalisation. For those who already understand normal forms, please understand that I'm trying to give practical guidelines, not theoretical strict definitions here.
When you're designing your tables (you ARE designing before you implement, aren't you?), you want to keep things fairly normalised. Now, what exactly does that mean?
First, and most importantly, every column in each table should depend on an individual instance of what that table is describing. For example, if you have a comments table and you want this table to also contain information about the user that posted the comment, say the user's name and tagline, you wouldn't actually store the username and tagline inside the comments table. Since I'm not very eloquent at describing this stuff, here's an example:
Code:CREATE TABLE users ( uid INT NOT NULL AUTO_INCREMENT, username VARCHAR(32) NOT NULL, tagline VARCHAR(64) DEFAULT '', -- ... rest of the fields here PRIMARY KEY(uid), UNIQUE(username) ); CREATE TABLE comments ( cid INT NOT NULL AUTO_INCREMENT, uid INT NOT NULL, -- in a proper RDBMS (which MySQL is NOT), you'd reference the users table here as a foreign key) pid INT NOT NULL, -- ditto comment_body TEXT, -- ... more fields PRIMARY KEY(cid), INDEX(pid) );
On with database normalisation concept #2 - don't store multiple values in a single column:
Let's say you have the users table above, and you decide that you want to store every IP address the user has ever logged in under. Now, a novice developer may think that this data belongs in the users table as well, since it depends directly on the user. They might opt to use a VARCHAR or TEXT field and store the values there in some fashion (separated by a delimiter, or perhaps as a serialized array). This is bad practice and leads to all sorts of issues, and also reduces the flexibility of your database. There are two 'correct' ways to accomplish this sort of one to many relationship. The first, and (IMO) correct way in this case is to create a separate table for IPs:
Code:CREATE TABLE user_ips ( uid INT NOT NULL, -- foreign key ip VARCHAR(15) NOT NULL, PRIMARY KEY(uid, ip), INDEX(ip) );
Now for another similar example to show the other technique. Let's say you're writing something like a blog, where you might have a number of posts as well as a number of categories, where each post can be in an arbitrary number of categories. For this you're going to want a separate table for both posts and categories, and you'd want to create a third table to map the two together (we'll use the users table from above):
Code:CREATE TABLE posts ( pid INT NOT NULL AUTO_INCREMENT, uid INT NOT NULL, -- again, foreign key definition would go here post_content TEXT, -- more... PRIMARY KEY(pid), INDEX(uid) ); CREATE TABLE categories ( cat_id INT NOT NULL AUTO_INCREMENT, name VARCHAR(64), -- etc... PRIMARY KEY(cat_id) ); CREATE TABLE cat_posts_map ( pid INT NOT NULL, -- FK cat_id INT NOT NULL, -- FK INDEX(pid), INDEX(cat_id) );
First, let's take our most recent example -- getting a single post and the categories it's in. What we need to do is map the three tables (posts, users, categories)...well actually four if we count the mapping table...into a single result table. There are two syntaxes for doing this. I'm only going to cover the conditional one, as I think it's easier to understand. If you want to look into the JOIN syntax, you can find it on the JOIN syntax page.
Now before we give some examples for this, let's populate our database with some data:
Code:INSERT INTO users (username, tagline) VALUES ('user1', 'im a test user'); INSERT INTO users(username, tagline) VALUES ('user2', 'im another test user'); INSERT INTO posts (uid, post_content) VALUES (1, 'test post'); INSERT INTO posts (uid, post_content) VALUES (1, 'another post'); INSERT INTO categories (name) VALUES ('test_cat'); INSERT INTO categories (name) VALUES ('another_cat'); INSERT INTO cat_posts_map (pid, cat_id) VALUES (1, 1); INSERT INTO cat_posts_map (pid, cat_id) VALUES (1, 2); -- put post 1 in both categories INSERT INTO comments (uid, pid, comment_body) VALUES (1, 1, 'comment 1'); INSERT INTO comments (uid, pid, comment_body) VALUES (2, 1, 'comment 2, new user');
Code:SELECT posts.*, users.*, categories.* FROM posts, users, categories, cat_posts_map WHERE posts.pid = 1 AND posts.uid = users.uid AND posts.pid = cat_posts_map.pid AND cat_posts_map.cat_id = categories.cat_id;
Code:+-----+-----+--------------+-----+----------+----------------+--------+-------------+ | pid | uid | post_content | uid | username | tagline | cat_id | name | +-----+-----+--------------+-----+----------+----------------+--------+-------------+ | 1 | 1 | test post | 1 | user1 | im a test user | 1 | test_cat | | 1 | 1 | test post | 1 | user1 | im a test user | 2 | another_cat | +-----+-----+--------------+-----+----------+----------------+--------+-------------+
The query to retrieve all the comments for a post is similar:
Code:SELECT comments.* FROM comments, posts -- we only care about the comment data here WHERE posts.pid = 1 AND comments.pid = posts.pid;
Code:+-----+-----+-----+---------------------+ | cid | uid | pid | comment_body | +-----+-----+-----+---------------------+ | 1 | 1 | 1 | comment 1 | | 2 | 2 | 1 | comment 2, new user | +-----+-----+-----+---------------------+
So I hope I didn't just waste an hour of my day. It's not simple stuff, but if you can grasp the concepts, you'll have an easier time designing databases and queries that are more complicated than a simple row/column relationship.0
-
01-25-2005, 06:03 PM #31Web Hosting Master
- Join Date
- Dec 2002
- Posts
- 1,304
in a proper RDBMS (which MySQL is NOT), you'd reference the users table here as a foreign key)
Do you have something against using InnoDB tables in mysql?"The only difference between a poor person and a rich person is what they do in their spare time."
"If youth is wasted on the young, then retirement is wasted on the old"0
-
03-22-2005, 01:20 PM #32Junior Guru
- Join Date
- Jan 2005
- Location
- Manchester, UK
- Posts
- 200
Re: How To : Improve Your PHP Programming
Originally posted by giropets
PHP Code:<?php
if(!file_exists("layout.inc.php")){exit("Error : LayOut File Missing");}else{include_once("layout.inc.php");}
?>
PHP Code:if(!file_exists("layout.inc.php")){exit("Error : LayOut File Missing");}else{include_once("layout.inc.php");}
PHP Code:(!file_exists("layout.inc.php")) ? exit("Error : LayOut File Missing") ? include_once("layout.inc.php");
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 :
PHP Code:<?php
mysql_query("INSERT INTO tableName ('id','name') VALUES('1','Mike')");
?>
PHP Code:<?php
mysql_query("INSERT INTO tableName ('id','name') VALUES('1','Mike')") or exit("MySQL Error : " . mysql_error());
?>
example, `id`,`name` .
Just wanted to point these out - ..
Splamoni
www.imgdoc.net - Free Image and Document Hosting!!0
-
03-22-2005, 04:28 PM #33Newbie
- Join Date
- Jan 2004
- Location
- K.S.A
- Posts
- 13
Re: How To : Improve Your PHP Programming
Originally posted by splamoni
so instead, use the more compact version..
PHP Code:(!file_exists("layout.inc.php")) ? exit("Error : LayOut File Missing") ? include_once("layout.inc.php");
PHP Code:(!file_exists('layout.inc.php')) ? exit('Error : LayOut File Missing') : include_once('layout.inc.php');
Because include() and require() are special language constructs, you must enclose them within a statement block if it's inside a conditional block.
Example 11-6. include() and conditional blocks
PHP Code:<?php
// This is WRONG and will not work as desired.
if ($condition)
include $file;
else
include $other;
// This is CORRECT.
if ($condition) {
include $file;
} else {
include $other;
}
?>
as for
This is incorrect, INSERT INTO table ($keys) VALUES ($values) ... $keys must be ` ` and $values must be ' '.
example, `id`,`name` .We don't need a reason to help people0
-
03-22-2005, 06:00 PM #34Junior Guru
- Join Date
- Jan 2005
- Location
- Manchester, UK
- Posts
- 200
Yea i apologize bout that double ? ,
its (if) ? true : false;
But about the ``, you dont have to put `key` etc, but it is better coding standards, plus i was correcting the original which was ' ' which wouldnt work.
And seeming as this is about improving php coding, the `` 's are better to use.
Thanks anyways,
Splamoni
http://www.imgdoc.net/ - Free Online Image and Document Hosting0
-
03-22-2005, 06:13 PM #35Junior Guru Wannabe
- Join Date
- May 2003
- Location
- United States
- Posts
- 63
Most everyone here can probably agree that I'm not the best programmer around, so thanks for your comments about that.
0
-
03-23-2005, 12:02 AM #36WHT Addict
- Join Date
- Feb 2005
- Location
- Seattle, Washington
- Posts
- 147
I would just like to point out that include|require(_once) are language constructs, so you do not need to use ( ) when using them. Instead, just do require_once 'File.php';
Another comment, unless text needs to be parsed(i.e. has \n or variables etc in it), you should always use ' for enclosing strings, instead of "
Also, it is better to do !isset($_POST['name']) instead of !$_POST[name] (do this for any var, not just $_POST).
Also, someone was using globals above, you should try and avoid using globals, its a horrible practice. Instead, pass the values to the array.0
-
04-03-2005, 01:55 PM #37Newbie
- Join Date
- Nov 2004
- Posts
- 23
And when you have a massive load on your server knowing how to optimize your script will be important.
The following link will tell you some teqniues.
http://www.php.lt/benchmark/phpbench.phphttp://DNSDigger.com - Shows what other sites is hosted on that IP/host/range.0
-
07-15-2005, 05:44 PM #38Newbie
- Join Date
- Oct 2004
- Posts
- 13
Re: Re: How To : Improve Your PHP Programming
Originally posted by websterworld
get a proper PHP editor such as PHPcoder or the one by zend . (which is great, I love it. )
it has a ton of time saving advantages such as syntax highlighting and line numbering, 'etc.
Eugene
You are talking about Zend Studio, right?Last edited by JonBlower; 07-15-2005 at 05:49 PM.
0
-
08-03-2005, 08:44 PM #39Junior Guru Wannabe
- Join Date
- Mar 2005
- Posts
- 32
Re: How To : Improve Your PHP Programming
Thanks for sharing the PHP expertise. I'm impressed with how PHP is apparently free and developed by folks all over the world (like Linux). When companies have their own software that they sell us along with their hosting (for example regarding forums or databases), and they charge for bandwidth as well, it's not always easy to view their software "upgrades" with suspicion when bandwidth consumption charges subsequently increase. At least with PHP there doesn't tend to be that potential conflict of interest, it would seem.
Might anyone here care to comment on whether PHPbb would be my best bet for creating a membership database, affordably? I'm hoping to gradually fill it up with over 50,000 members (if not more, ideally), and to have considerable data on each one (that they could include and update, in their own language but more often than not in Spanish). Then when I need to find members with certain characteristics, I can search the database and mass-mail the ones who satisfy the criteria.
Ideally I could offer cookies so that they wouldn't have to log in each time they visit, and so that I could tailor the interface precisely for them and folks of their demographics to make it more interesting (and to streamline communications, requiring as few clicks as possible). I'd like to be able to represent in good conscience that the data's secure, too. Unfortunately I'm not a computer programmer as a specialist, but I know html pretty well. I'm tempted to get a hosting account somewhere and gradually learn the ropes with the assistance of the host, but it may be that PHPbb isn't really the most suitable language and I should know that before selecting a host. Affordability is a significant concern though. Any thoughts, friends?0
-
01-04-2006, 01:14 PM #40Junior Guru Wannabe
- Join Date
- Jan 2006
- Posts
- 34
0
-
03-07-2006, 08:23 PM #41New Member
- Join Date
- Mar 2006
- Location
- Newcastle Australia
- Posts
- 1
A great and useful "How-to", I learned a number of new things.
Why not collect it all in one file and put a link to it on your web-site.
Then people could get all the goodies without a lot of cutting and pasting.0
-
03-18-2006, 09:20 PM #42New Member
- Join Date
- Mar 2006
- Location
- Canada
- Posts
- 2
I have to agree,... not boring at all!
Nice work!0
-
03-30-2006, 03:20 AM #43Newbie
- Join Date
- Mar 2006
- Posts
- 9
Thanks a lot for your tips and tutorial.
I have done simple shop and only one page just not totally functioning.After the checkout.Customers fill the required fields and the last page they will send what they have bought.I have changed it for a now as a formular and it comes to my email but has so much code and &&& symbos etc. Actuall it does not send to customers email too.
Could you please help for rebuilding this order.php . Checkout etc functions but just the last actions for order.php does not function. It does not send the photo etc.what they have .I have made test order and comes 5 pages code to my email.
Greetings0
-
03-30-2006, 03:45 AM #44Junior Guru
- Join Date
- Jan 2005
- Location
- Manchester, UK
- Posts
- 200
Originally Posted by $_patch
Haha, you could just use $rand = rand(1, 3);█ Software developer, web designer, and general clever-clogs.
█ C#, XHTML, CSS, PHP, MySQL, MsSQL, T-SQL, Photoshop & more0
-
04-05-2006, 03:47 PM #45Junior Guru Wannabe
- Join Date
- Jan 2006
- Posts
- 46
does this mean you make a function to randomly return 1 2 or 3?
Haha, you could just use $rand = rand(1, 3);0
-
04-05-2006, 04:25 PM #46Web Hosting Master
- Join Date
- Jul 2003
- Location
- Kuwait
- Posts
- 5,104
Okay, maybe I should correct some false statements here.
* Commas are apaprently faster than periods when it comes to concatenation
For example, you cannot do this:
PHP Code:$string = 'foo','bar'; # !!! Syntax error!!
PHP Code:$string = 'foo';
echo $string,'bar';
PHP Code:echo ($string,'bar');
* When using comparison operators, you can either use == or === The latter will check for the type as well as the value and it is faster.
* switch/case is faster than an if condition
* Type cast any foreach arguments to avoid error messages
PHP Code:$result = someFunction();
if (is_array($result))
{
foreach($result as $foo => $bar)
{
/* ... */
}
}
* If you prepend a function with an AT sign (@), it will not spit out any errors. The same applies to user defined functions.
I haven't had time to read the rest -- but these stood out.0
-
04-05-2006, 06:04 PM #47Junior Guru
- Join Date
- Jan 2005
- Location
- Manchester, UK
- Posts
- 200
Originally Posted by RACKSET
Warning: rand() expects exactly 2 parameters, 1 given in /home/imdsm/public_html/dev/test.php on line 3
You must remember that the way rand works, is it takes a value from between "min" and "max":
int rand ( [int min, int max] )
You can view more information about this at http://uk2.php.net/rand
█ Software developer, web designer, and general clever-clogs.
█ C#, XHTML, CSS, PHP, MySQL, MsSQL, T-SQL, Photoshop & more0
-
04-05-2006, 06:09 PM #48Junior Guru
- Join Date
- Jan 2005
- Location
- Manchester, UK
- Posts
- 200
Originally Posted by fyrestrtr
PHP Code:<?php
$result = mysql_query("select * from table");
$numrows = @mysql_num_rows($result);
/* or a better way to do this, would be to use type casting. */
$result = mysql_query("select * from table");
$numrows = (int)@mysql_num_rows($result);
/* in this case, if there aren't any rows returned, php wont error but instead return 0 instead of false. */
?>
Hope this is of some use to you.█ Software developer, web designer, and general clever-clogs.
█ C#, XHTML, CSS, PHP, MySQL, MsSQL, T-SQL, Photoshop & more0
-
07-02-2006, 09:39 AM #49New Member
- Join Date
- Apr 2005
- Posts
- 4
A lot has been said, and a lot has been corrected, there are still some small things I'd like to point out tho...
1. Heredoc
PHP 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;
?>
2. Variables
1. Use variable names that make sense.
a) $string is a string, and $string_array is an array for example. $flag is a flag...
PHP Code:// boolean
$bIsActive = FALSE;
$bNeedsRefresh = TRUE;
// integer
$iPhoneNumber = 042323232;
$iRandNum = rand(3,6);
// string
$sErrorMsg = 'This is an error';
$sUserName = 'JeanM';
// query
$qUserInfo = mysql_query("SELECT * FROM user WHERE user = '".$sUserName."'");
// array
$aSmilies = array(':D',':(',':P');
$aUserInfo = mysql_fetch_assoc($qUserInfo);
1. Use the first letter to tell what kind of variable we are dealing with $un -> $sun
2. Don't use short variables like $sun but instead write full names $sun -> $susername
3. Use a case letter whenever a new word starts, this makes it easier to read: $susername -> $sUserName
This makes coding and using variables A LOT easier and it really isn't more work. Yes you will get longer variables but who cares, what matters most is that you still understand your script 6 months after you first created the script.
3. Quotation
Using Single Quotes VS. Duoble Quotes
some poeple don't know the difference between single and double quotes..
single quotes are faster than double ones because it wont parse variables while the double quotes will look for variables to parse ..
so if you have only hardcoded text, use single quotes but if you have variables use duoble quotes..
example:
PHP Code:$var = 'value';
echo 'this is $var'; //prints "this is $var"
echo "this is $var"; //prints "this is value"
PHP Code:// parsing a string
echo 'using single quotes is faster';
// string with a variable
$sPossible = 'possible';
echo "This would be $sPossible";
$sMuchBetter = 'much better';
echo 'But this would be '.$sMuchBetter;
One thing to watch out for (which as been stated before in this thread) is that using linebreaks like \n or \r is not possible within single quotes, in this case you could to the following:
PHP Code:echo "Text with a line break\n"
PHP Code:echo 'Text with a line break'."\n"
This is incorrect, INSERT INTO table ($keys) VALUES ($values) ... $keys must be ` ` and $values must be ' '.
example, `id`,`name` .
PHP Code:mysql_query("SELECT * FROM users ORDER BY order");
Last edited by JeanM; 07-02-2006 at 09:43 AM.
0
-
07-02-2006, 04:28 PM #50Web Hosting Master
- Join Date
- Dec 2002
- Posts
- 1,304
JeanM,
I agree with what you said, with one exception. The microsoft-like-way of being annoyingly obnoxious with variable names, table names, query names, etc..
$myhouse = 'nice';
$sMyHouse 'nice';
There is no purpose to this whatsoever.
Similarly, in access (offtopic but I think thats where this mess started), you see things like:
tblPerson
qFindPeople
sString
Its silly. As if I didnt know tblPerson was a table, or that qFindPeople was a query. I think you should give variables / objects / etc sensible names, but prefixing them with characters that are supposed to show their purpose is meaningless, redundant, and obnoxious for the 'rest of us'.
My other comment on HEREDOC... I love HEREDOC, because I dont have to worry about quotation rules. I just punch out what I want to put in.. I use it a lot for queries - I dont use it to output html / text."The only difference between a poor person and a rich person is what they do in their spare time."
"If youth is wasted on the young, then retirement is wasted on the old"0