TalkPHP
 
 
Account Login
Latest Articles
» The basic usage of PHPTAL, a XML/XHTML template library for PHP
» Vulnerable methods and the areas they are commonly trusted in.
» Simple way to protect a form from bot
» The Basics On: How Session Stealing Works
» How to keep your forms from double posting data
IRC Channel
IRC Speech Bubble Join the friendly bunch on IRC...
(#TalkPHP on Freenode)

...Also available via a web interface.

See this thread for information on the TalkPHP Free Hugs Initiative™. Subject to availability.
Associates
Associates
CSS Tutorials
Reply
 
LinkBack Thread Tools Search this Thread Display Modes
Old 06-03-2005, 02:27 PM   #1 (permalink)
The Acquainted
 
Join Date: May 2005
Posts: 106
Thanks: 0
jaswinder_rana is on a distinguished road
Default PHP/MySQL tips and tricks

Hi,
This thread is dedicated to all the tips and trick to ease the usage of PHP/MySQl.

Feel free to list or ask about any Trick you use or want to know.

print_r()
This function great to debug large arrays. It can be used for string or other variables too, but its real handy with arrays. in every project i always make a function then include that file(which includes that function) in every file. it makes it real easy to debug problems.
The normal output from this function is really cluttery and is hard to figure things out. But, when used with <pre></pre> tags, its realy useful.
function printR($var)
{
echo '<pre>';
print_r($var);
echo '</pre>';
}
Will list more functions as i remember them.

Also point out any errors that i migh thave made.

Reading from a file

Ther are many methods of reading from a file. it depends what you want to do.
1) file('filename'). it reads the whole file and return an array with each line as new index in array

2) file_get_contents('filename'). it returns the whole file.

the above 2 are useful if you just wana read the file. it saves you from the hassle of opening, reading and closing files.

also, its always a good idea to check if the file exists, before doing anything with it. it just saves you from making errors. so you do something like
if(file_exists('filename'))
echo file_get_contents('filename');

Writing to a file

file-put_contents('filename','data') will write the 'data' to the file. This again saves fromthe hassle of opening, writing and closing the file.

mysql_errno()

You can use this feature to tackle with the MySQL errors.
for eg.
PHP Code:
function dbSelect($dbName)
{
   if(!@
mysql_select_db($dbName))
    return 
FALSE;
  else
   return 
TRUE;
}
function 
dbErrorNo()
{
  return 
mysql_errno();
}
if(!
dbSelect('wrong_db_name'))
{
  if(
dbErrorNo() == '1049')
  {
    echo 
'Database selection problem.';
  }

Why this is handy?
Suppose, you have to insert a new user in database and before inserting you have to check, if that username already exists or not. To check this, first you have to run a a select statement to see if MySQL returns a record with that username. If records is returned it means user already exists. If not then we can safely insert the record in database.

Now it needs to access database twice, which takes up resources (especially on large scale website).

So, now we'll use our new solution. For this new solution to work, the username field should be set to unique, it means, no other user can have the same username.

Then we run our insert statement. If the username already exists, then it won't let the query run and will generate an error, which will say "Duplicate entry 'username' for key 1". and the error number will be 1062;
now we can say
PHP Code:
if(dbError() == '1062')
{
  echo 
'Sorry, username already exists.';

This will save some processing time.
__________________
---------------------------
Errors = Improved Programming.
Portfolio

Last edited by jaswinder_rana : 06-04-2005 at 02:42 PM.
Send a message via MSN to jaswinder_rana
jaswinder_rana is offline  
Reply With Quote
Old 06-05-2005, 01:52 AM   #2 (permalink)
The Acquainted
 
Join Date: May 2005
Posts: 106
Thanks: 0
jaswinder_rana is on a distinguished road
Default

Include vs readfile
Both are kind of same. The difference is in the speed and time taken for execution. Readfile is more faster than include.

BUT, usage of both are different

test1.php
PHP Code:
<?php
  
echo 'test<br>';
?>
<HTML>
<form>
</form>
</html>

Now if you do
include.php('test1.php'); it'll first execute the PHP, prouce the result and then get the content. so the result will be
Quote:
test
<HTML>
<form>
</form>
</html>
readfile.php('test1.php') will return everything in the file. It'll NOT execute the PHP. so the result will be
Quote:
<?php
echo 'test<br>';
?>
<HTML>
<form>
</form>
</html>

Conclusion
If you want to include static files (with no PHP DYNAMIC CONTENT), use readfile. its more faster.

if you want to include a fie which includes dynamic contents (like test1.php) then use include.
__________________
---------------------------
Errors = Improved Programming.
Portfolio
Send a message via MSN to jaswinder_rana
jaswinder_rana is offline  
Reply With Quote
Old 06-05-2005, 02:03 AM   #3 (permalink)
The Acquainted
 
Join Date: May 2005
Posts: 106
Thanks: 0
jaswinder_rana is on a distinguished road
Default

Commas in echo
This might be the first time you are seeing this. you can echo something like
PHP Code:
$str 'sentence.';
echo 
'This ','is ','a ',$str
it'll print This is a senetence.. Yes, it works like concatenation but it does not concate strings, it just print everything to buffer.

and if you do
PHP Code:
$str 'sentence.';
echo 
'This '.'is '.'a '.$str
while using periods, it'll first concatenate strings and then print them out.

So, using commas is more faster than using periods.

Note: it only works in echo.
YOU CANNOT DO THIS::
$str = 'This ','is ','a ','sentence.';//THIS IS WRONG SYNTAX
__________________
---------------------------
Errors = Improved Programming.
Portfolio
Send a message via MSN to jaswinder_rana
jaswinder_rana is offline  
Reply With Quote
Old 06-05-2005, 05:15 PM   #4 (permalink)
The Acquainted
 
Join Date: May 2005
Posts: 106
Thanks: 0
jaswinder_rana is on a distinguished road
Default

using variables to store and call functions

You can use variables to store function names and then call them.
PHP Code:
$functionName 'sha1';
echo 
$functionName('string');

$functionName 'md5';
echo 
$functionName('string'); 
Where its useful?
Like the example i shown you. You can store an encrypting function the nuse it alter. Then suppose somebody wants you to change all the encoding functions throughout the site
from
md5()

to
sha1()

So, if you can have a variable in which you can store function name and then store it in your config file. Then whenever you want to change it just change it in your config file and it'll change everywhere globally.
__________________
---------------------------
Errors = Improved Programming.
Portfolio
Send a message via MSN to jaswinder_rana
jaswinder_rana is offline  
Reply With Quote
Old 06-06-2005, 10:10 PM   #5 (permalink)
The Acquainted
 
Join Date: May 2005
Posts: 106
Thanks: 0
jaswinder_rana is on a distinguished road
Default

Ternary Operator
This is great operator. its actually an if-else statement, but they gave it a fancy name.
the syntax is
(condition)?this:else;

it says if the condition is TRUE then do this or do else

example:
PHP Code:
$flag TRUE;
$msg = ($flag)?'Hired':'Fired'
The examples says, if flag is true then store 'Hired' in $msg else store 'Fired'.

The more general example is using different colors for rows
PHP Code:
$color '203030';
$flag TRUE;
echo 
'<table>';
while(
$flag)
{
  echo 
'<tr bgcolor="'.(($color=='203030')?'404040':'203030').'"><td> Row with different color</td></tr>';
}
echo 
'</table>'
Hope this was helpful
__________________
---------------------------
Errors = Improved Programming.
Portfolio
Send a message via MSN to jaswinder_rana
jaswinder_rana is offline  
Reply With Quote
Old 06-14-2005, 02:27 AM   #6 (permalink)
The Acquainted
 
Join Date: May 2005
Posts: 106
Thanks: 0
jaswinder_rana is on a distinguished road
Default

Save image using file_get_contents

I am using talkphp logo for this example, hoping Ryan wouldn't mind :D

I din't know i could do this until i did. you can rad an image file and then save it. its like saving images automatically.
PHP Code:
$url 'http://www.talkphp.com/images/talkphp/logo2.gif'//MAKE SURE http is there

$contents = @file_get_contents($url);
if(!empty(
$contents))
{
 
$file $_SERVER['DOCUMENT_ROOT'].'/images/saved.gif';//Make sure images directory exists
 
$fh  = @fopen($file,'w');
 if(
$fh)
 {
   
fwrite($fh,$contents);
   
fclose($fh);
 }

and that would save file to your directory. Might not mean anything to you, but its good to know, coz i just used it today in my project. Ofcourse, legal rights should be taken care of.
__________________
---------------------------
Errors = Improved Programming.
Portfolio
Send a message via MSN to jaswinder_rana
jaswinder_rana is offline  
Reply With Quote
Old 07-17-2005, 01:56 AM   #7 (permalink)
The Acquainted
 
Join Date: May 2005
Posts: 106
Thanks: 0
jaswinder_rana is on a distinguished road
Default

Regular Expression
there are 2 types of functions for matching regular expressions

ereg, and preg_match

ereg, is PHP's regular expression matching function (as far as i know, can be wrong)
and preg_match is based on perl regular expression matching.

Both consume time, so try to use other this like substr, strstr if they can be applicable in your situation, but if its must to use regular expression then use
preg_match()
its twice as much faster than ereg.

theres nothing which you can't do in both, just speed difference is a lot, and it counts in fairly large applications.
__________________
---------------------------
Errors = Improved Programming.
Portfolio
Send a message via MSN to jaswinder_rana
jaswinder_rana is offline  
Reply With Quote
Reply



Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


All times are GMT. The time now is 02:38 PM.

 
     

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0
Inactive Reminders By Icora Web Design