Some Useful Tips That Every PHP Programmers Should Know

Some Useful Tips That Every PHP Programmers Should Know
There are few useful and important tips for PHP programming which I collected here for every PHP developers.


Tip 1: MySQL Connection Class :-

The majority of web applications I've worked with over the past year have used some variation of this connection class:


class DB { function DB() { $this->host = "localhost"; // your host $this->db = "myDatabase"; // your database $this->user = "root"; // your username $this->pass = "mysql"; // your password $this->link = mysql_connect($this->host, $this->user,
$this->pass); mysql_select_db($this->db); }} // calls it to action$db = new $DB;Simply edit the variables and include it in your files. For that, you dont need to create a different connection class. Now, you can easily connect to your database without any extra effort.

$result = mysql_query("SELECT * FROM table ORDER BY id ASC LIMIT 0,10");
Tip 2: Dealing with Magic Quotes :-

In PHP you can apply slashes to your $_POST data for security purposes. This is an important measure to prevent SQL injections. But, slashes in your scripts can wreak havoc. This is an easy method for dealing with them. What will happen if the magic quotes directive is not enabled?


function magicQuotes($post) { if (get_magic_quotes_gpc()) { if (is_array($post) { return array_map('stripslashes',$post); } else { return stripslashes($post); } } else { return; // magic quotes are not ON so we do nothing } }
You can check above scripts to see if magic quotes is enabled. If They are, it will determine if your $_POST data is an array and then it will strip the slashes accordingly. Tip 3 : Safely Query Database with mysql_real_escape_string :-
When you are ready to query your database you will need to escape special characters for safety's sake by adding slashes. We apply these before we insert variables into our database. And we need to determine which version of PHP you are running first:

function escapeString($post) { if (phpversion() >= '4.3.0') { return array_map('mysql_real_escape_string',$post); } else { return array_map('mysql_escape_string',$post);
} }
SHARE

About Mitesh Soni

I am Web Analyst I love to analyse the web for the betterment of businesses and providing information to my blog reader. I love to write about trending technologies, specially mobile technologies.
    Blogger Comment
    Facebook Comment

2 comments:

  1. Everything's fine, but not reading from block quotes. Please install a syntax highlighter or at least use <pre> and <code> tags.

    ReplyDelete