View Full Version : Learn PHP/MySQL Feedback Thread
fivefeet8
08-27-08, 04:17 PM
i typically use double quotes and escape them when i want them in the HTML. but single quotes would probably be a better idea.
Double quotes allows you to insert php variables directly in the string without concatenation. Ie.
$var = 'text';
echo "<input type='$var' />";
The php documentation seems to indicate that single quote strings are faster to parse though since the interpreter doesn't need to scan the string for php variables. You can also use double quotes for the php string and use single quotes for the html like above.
The primary issue with using either single or double quotes with HTML within a string is when it comes to javascript function calls and their arguments when the arguments are javascript strings. In which case, either concatenation or quote escapes will work.
Monolyth
08-27-08, 04:58 PM
I say a full OOP thread is the best, the sooner people get comfortable with it the sooner they will be better PHP programmers. You can hack up PHP code, but once you step into OOP as well as object model development you can really do some cool things that will make your life down the road 20x easier. ;)
t3hl33td4rg0n
08-28-08, 12:13 PM
OOP was a struggle for me at first because my first programming expereinces came with GWBASIC when i was in my early teens, so procedural programming didn't come to me as second nature. The only reason i knew about it was browsing php.net and stumbled upon "class". I read about it and thought to myself "this is cool! how the hell do i use it?!"
I looked at a couple tutorials and was having a hard time grasping it until I found one specific article about it and I eventually figured it out and spending an entire day making my own from scratch... So essentially, beyond that little tutorial I found, ive been learning on the fly. Even now, I'm just hoping I'm doing it right.
Heres a template class I've been working on and off for a short while.... Any logical flaws in this way of implementing classes?
class coreTpl extends coreDb {
public $tpl;
public $tpl_name;
public $tpl_fdir;
public $tpl_rdir;
public $tpl_ftpl;
public $tpl_fcss;
public $tpl_prts;
public function getTemplate ($name, $path) {
$s = 'SELECT * FROM `tpl` WHERE `name` = "'.$name.'" LIMIT 1'; // Get Template Info
$q = mysqli_query ($this->db, $s);
$r = mysqli_fetch_assoc ($q);
$this->tpl_name = $r['name'];
$this->tpl_fdir = $path.$r['dir'];
$this->tpl_rdir = $path;
$this->tpl_ftpl = $r['tpl'];
$this->tpl_fcss = $r['css'];
$this->tpl = file_get_contents ($this->tpl_fdir.$this->tpl_ftpl);
$this->tpl = coreTpl::rplPathStr ($this->tpl, $this->tpl_fdir);
}
public function inConStd ($loc, $name, $style, $sortBy, $SortType, $offset, $limit, $where) { // Grab Dynamic Content, And Insert Into Template
// Based on Loc
$conD = coreTpl::inConStyle($style); // Get Content Style HTML
$out = '';
$s = 'SELECT * FROM `con` WHERE `name` = "'.$name.'" ORDER BY `'.$sortBy.'` '.$SortType.' LIMIT '.$offset.', '.$limit;
$q = mysqli_query ($this->db, $s) or die (mysqli_error ($this->db));
while ($r = mysqli_fetch_assoc($q)) { // <-- Outer Loop: Take Row And Append HTML Data Then Content
$out .= $conD['top']; // Ex: TOP { Style0 | Part0 | Style1 | Part1 } BOTTOM
for ($x = 0; $x < $conD['parts']; $x++) { // <-- Inner Loop: Loop through array until Style Parts Meets Up With
$part = 'part'.$x; // Content Parts
$out .= $conD[$part]; // <-- Append HTML Before Content Text
$out .= $r[$part]; // <-- Append Content Text
}
$out .= $conD['bottom']; // <-- Append Bottom HTML After Last Part Is Appended
}
/* Out is the dynamic content and its associated style HTML, which will be inserted into the template where $loc specifies. The output will look
something like this:
Style TOP { Style Part0 | Content Part0 | Style Part1 | Content Part1 | Style Part2 | Content Part2 } Style BOTTOM
Style Can be any HTML, like a table, div, or just about anything else and is considered a text wrapper with all the styling HTML whereas the
content text is the actual dynamic text, which can be HTML as well. The number of parts is actually determined in the styling table. The inner loop
will stop at the last part based on that number. So if parts >> parts is 7 then it will loop 7 times through the content data like part0 to part6
columns in the associative array. An example could be something like this.
Parts = 3
Style = 'My Style'
Top = <table><tr>
part0 = <td>
part1 = </td><td>
part2 = </td></tr><tr><td colspan="2">
Bottom = </td></tr></table>
Content = 'My Example'
Part0 = FOO
Part1 = BAR
Part2 = BAZ
Call The Method As Specified $tpl->inConStd ('<!-- PLACEHOLDER -->', 'My Example', 'My Style', 'date', 'DESC', 0, 1);
And the Result Will Be:
<table><tr><td>FOO</td><td>BAR</td></tr><tr><td colspan="2">BAZ</td></tr></table>
This is just a simple example, calling this method based on your criteria will retrieve 1 or more records and will loop through all rows
returned form the query. You can also use whatever content you want with whatever style you want as well. You can also mix and match content
in whatever way you choose. For example, if you choose to implement the user the ability to use his/her own template style and color scheme or whatever,
it can be done very easily. Implement a little AJAX, and the user can do play with the content and page theme on the fly. Another reason is that you can
easily throw in as much content as you want, anywhere you want, and filter it in any way shape or form. In any case, with the content iteration methods
the site layout, content, and functionality is completely freeform. One last example, if you want to throw in a quick snippet of info form another page
that would normally not be on the site homepage, like a new users profile and all the features associated with profile accessability; and maybe put that
just above the main content because this new user is important.
*/
$out = coreTpl::rplPathStr ($out, $this->tpl_fdir); // Replace {{PATH}} and {{LIBPATH}} strings to relative locale
switch ($where) { // Insert Content Into Template where specified in $loc
case 'before':
$this->tpl = str_replace($loc, $out.$loc, $this->tpl);
break;
case 'after':
$this->tpl = str_replace($loc, $loc.$out, $this->tpl);
break;
default:
$this->tpl = str_replace($loc, $out.$loc, $this->tpl);
break;
}
}
private function inConStyle ($name) { // Get The Content Style Code
$s = 'SELECT * FROM `parts` WHERE `name` = "'.$name.'" LIMIT 1';
$q = mysqli_query($this->db, $s) or die(mysql_error());
$r = mysqli_fetch_assoc($q);
return $r;
}
private function rplPathStr ($str, $path) { // Replace Strings To Avoid Directory Confustion (WORKS)
$str = str_replace('{{LIBPATH}}', $this->tpl_rdir, $str); // Will replace {{LIBPATH}} in Template with Current Relative File Path
$str = str_replace('{{PATH}}', $path, $str); // Will replace {{PATH}} in Template with Current Relative File Path
return $str;
}
public function putHtml ($id, $src) {
}
}
And a user authentication class (pre-alpha/very unfinished):
class coreUsr extends coreDb {
public $usr_name;
public $usr_passwd;
public $usr_sid;
public $usr_auth;
public $usr_lvl;
public $usr_perm;
public function usrChkAuth ($name, $passwd) {
$s = 'SELECT * FROM `usr` WHERE `name` = "'.$name.'" LIMIT 1';
$q = mysqli_query($this->db, $s) or die(mysqli_error($this->db));
$r = mysqli_fetch_assoc($q);
if ($name == $r['name']) {
$userName = true;
} else {
$userName = false;
}
if ($passwd == $r['passwd']) {
$userPass = true;
} else {
$userPass = false;
}
if ($userName && $userPass) {
$this->usr_auth = true;
$this->usr_name = $r['name'];
$this->usr_passwd = $passwd;
$this->usr_lvl = $r['lvl'];
$this->usr_sid = session_id();
$this->usr_perm['addcon'] = $r['addcon'];
$this->usr_perm['updcon'] = $r['updcon'];
$this->usr_perm['delcon'] = $r['delcon'];
return true;
} else {
$this->usr_auth = false;
return false;
}
}
public function usrLogin () {
}
}
.... And as far as using what type of quotes, I always use single quotes and concatenation. I find it easier to proofread that way, and there is much less concern with escaping any strings, since theres a lot more double quotes going inside a string than single quotes.
fivefeet8
08-28-08, 04:01 PM
Your object definitions don't have a class constructor. Most OOP languages use constructors to initialize object variables. PHP is far more lenient in this regard and allows variables to be created on the whim without initialization. It does throw a bunch of warnings though.
A discussion about classes and objects also needs to touch on passing variables by reference and by value. PHP by default, makes all variables passed into functions by reference. There is a value in the php.ini to change it to pass by value. You can then pass by reference only when you explicitly do so. Ie.
function passbyreference(&$str, &$obj, Array &$arr){
// do something
}
All the arguments in that function will be passed by reference. According to the PHP.ini file, the default behavior of passing by reference will be deprecated in future versions of PHP(PHP6). It's wise to make your functions explicitly pass by reference if that's how you designed them to function. This default behavior caused me some headaches when my object variables were changing values when I didn't want them to after being passed into a function.
I'm currently taking a PHP and MySQL class so, if anyone that's wanting to learn PHP and MySQL is interested I'd be happy to post our labs and projects from class here.
Just let me know and I'll get to it.
LovingSticky
09-17-08, 05:26 PM
nice thread so far mate, i have only one small concern so far; you are using double quotes in your variables, tho this is ok to do and works fine it can lead to hassles later especially if you want to include a double quote in the html output, for example..
$test = "hello";
$output = "<a href="http://someurl.com">" . $test;
the above snippet will break unless the double quotes inside the html link are escaped with a \
single quotes however do not have this problem..
$test = 'hello';
$output = '<a href="http://someurl.com">' . $test;
Well, difference between single and double quotes is that double quotes get parsed, while single quotes do not. Ie. that if you do not need PHP to parse your strings, you should NOT use double quotes.
You should also not use [dot] to concat strings, much faster is to use comma, as it does not concat them, but just echoes them.
So, this is fastest:
echo '1', $itemid;
This is slower:
echo "1$itemid";
And this would be slowest:
echo "1".$itemid;
All those examples produce same result, of course.
You should also not use [dot] to concat strings, much faster is to use comma, as it does not concat them, but just echoes them.
So, this is fastest:
echo '1', $itemid;
This is slower:
echo "1$itemid";
And this would be slowest:
echo "1".$itemid;
All those examples produce same result, of course.
I haven't tried it, but it seems that the , concat is not actually concatenation but a separator for multiple arguments to echo, and thus is not a general purpose replacement for . concatenation. It's a useful suggestion for using echo, but keep in mind that premature optimization is the root of all evil so obfuscating your code to take advantage of this is probably not a good idea (unless of course you discover that you're taking a significant performance hit from that code, but then that wouldn't be premature optimization either;)). Also, it doesn't apply to the example because the result of the concatenation is being assigned to a variable, not echo'd.
So I guess my point is that it's a useful tip, but your statement that "You should also not use [dot] to concat strings" is not correct without qualification.
LovingSticky
09-17-08, 06:52 PM
"You should also not use [dot] to concat strings" is not correct without qualification.
Well, I think some things are pretty clear and do not have to be described in detail ;) Like "You should also not use [dot] to concat strings unless you really need it"
What is important:
- content of "" gets parsed
- content of '' does not
Well, I think some things are pretty clear and do not have to be described in detail ;) Like "You should also not use [dot] to concat strings unless you really need it"
Yeah, no problem. I was just afraid a newbie might misinterpret that as a general replacement for string concatenation and be really confused when they got syntax errors.:)
im sorry i have been tremendously busy with school. i will get to the tutorial asap. :(
DiscipleDOC
09-25-08, 06:04 PM
im sorry i have been tremendously busy with school. i will get to the tutorial asap. :(
Slacker!
:p
Slacker!
:p
lol grad school sucks man.
Bearclaw
09-28-08, 12:36 AM
Same here. Between work and night school, I haven't had anytime for anything. :(
Same here. Between work and night school, I haven't had anytime for anything. :(
Same here. Full time job, night school... actually I'm sitting in PHP with MySQL class right now :D
magstudios
01-23-09, 05:22 AM
Hi nice discussion for Software Development in PHP and MYsql the point and Topics the view of all member's who joined this thread are very good i really enjoy it.
thanks
MAG STUDIOS
t3hl33td4rg0n
01-31-09, 06:38 PM
lol, i totally forgot about this thing....
Well, when i was trying to figure out how to do OOP in PHP, I perused several tutorials, but this is the one that made me understand it clearly.
http://www.codewalkers.com/c/a/Programming-Basics/Beginning-Object-Oriented-Programming-in-PHP/
lol, i totally forgot about this thing....
Well, when i was trying to figure out how to do OOP in PHP, I perused several tutorials, but this is the one that made me understand it clearly.
http://www.codewalkers.com/c/a/Programming-Basics/Beginning-Object-Oriented-Programming-in-PHP/
i have worked with OOP and have a lot of code written. let me know if you need help with anything :)
fivefeet8
11-24-09, 07:36 PM
PHP 5.3 now supports namespaces. It would be good to have a discussion on the practical use of them. Also, if you're going to talk about OOP, then the difference between using "require()" and "require_once()" should be discussed in the context of OOP.
PHP 5.3 now supports namespaces. It would be good to have a discussion on the practical use of them. Also, if you're going to talk about OOP, then the difference between using "require()" and "require_once()" should be discussed in the context of OOP.
Sounds good.
Yes, I plan to devote some time to OOP. I may have some others contribute to that topic as well. If you're interested in writing some, let me know.
Bump. I need to bring this thing back. Hopefully I will get another section up soon. Next will be functions probably. Sucks it was almost a year since I did the last one. :(
nice thread so far mate, i have only one small concern so far; you are using double quotes in your variables, tho this is ok to do and works fine it can lead to hassles later especially if you want to include a double quote in the html output, for example..
$test = "hello";
$output = "<a href="http://someurl.com">" . $test;
the above snippet will break unless the double quotes inside the html link are escaped with a \
single quotes however do not have this problem..
$test = 'hello';
$output = '<a href="http://someurl.com">' . $test;
I'll help bring the thread back to life :D
Working with PHP on a daily basis in a production environment I myself can't think of any instances where the HTML that is being output is something that is anywhere near the size of this example. That just may be me but... I find that whenever I'm outputting HTML with PHP I find the easiest way to do it is via a HEREDOC.
$output = <<<HTML
<html>
<head></head>
<body>
$variable is a variable
{$variable[0]} is a an array element
I can use "Double Quotes" or 'Single Quotes' without worry.
</body>
</html>
HTML;
The one issue rookies run into is trying to format their code to look all nice in their IDE.
This works:
$output = <<<HTML
Some content
HTML;
This Doesn't:
(tab here) $output = <<<HTML
(2 tabs here) Some Content
(tab here) HTML;
Spaces of any kind prior to the closing HTML delimiter will break it.
Vin - If you need any real world examples of OOP with PHP I'd be glad to supply some. I have some pretty nifty abstraction via inclusion and dynamic class instantiation examples I could copy and paste right from work.
Nice. Maybe we should start an OOP PHP thread. Good idea?
DiscipleDOC
11-03-10, 05:17 PM
Nice. Maybe we should start an OOP PHP thread. Good idea?
I'm down with OOP.
:bleh:
Nice. Maybe we should start an OOP PHP thread. Good idea?
If you're going to IMO it would be best to show people how to implement design patterns.
I would go with either the decorator or factory patterns. If people can wrap their head around those they can wrap their head around OOP in general and yet neither is overly difficult.
vBulletin® v3.7.1, Copyright ©2000-2012, Jelsoft Enterprises Ltd.