Top 10 PHP Tips And Tricks For Beginners

Top 10 PHP Tips And Tricks For Beginners

PHP is one of the most loved and widely used programming languages that developers love to build their website. So that I want to say something about PHP coding strategy and much more. These strategies will differently help you.

For example, some useful tips and techniques that can be used to improve and optimize your PHP code, because every PHP developer want tips to improve there coding style and knowledge.

Don't use require, require_once, include or include_once

Almost all developers, use this way to handle external files. Your script should be including various files on top, like class libraries, files for utility and helper functions, etc like this :

require_once('inclides/Configure.php');
require_once('inclides/Database.php');
require_once('class/general_functions.php');

This is rather primitive. So that, you need to do this in a different way and the code needs to be more flexible. Write up helper functions to include things more easily. Let's take an example :

function include_class($class_name)
{
    //path to the class file
    $path = ROOT . '/include/' . $class_name . '.php');
    if(file_exists($path)) {
       require_once( $path );
    }
}
 
include_class('Configure');
include_class('Database');

There are a lot of things that can be done with this.

Loading...

Create a class for repeated tasks

Object-oriented programming is a powerful programming style for the flex coding and less work for a huge task as well as for the repeated task. Object-oriented programming is considered to be more advanced and efficient than the procedural style of programming. Object-oriented programming has several advantages over the conventional or procedural style of programming. Classes and objects are the two main aspects of object-oriented programming.

class Rectangle
{
    // Declare  properties
    public $length = 0;
    public $width = 0;
    
    // Method to get the perimeter
    public function getPerimeter(){
        return (2 * ($this->length + $this->width));
    }
    
    // Method to get the area
    public function getArea(){
        return ($this->length * $this->width);
    }
}

Once a class has been defined, then create another PHP file to get access of this class with the object:

require "Rectangle.php"; // Include class definition
 
$obj_rec = new Rectangle; // Create a new object from Rectangle class
$obj->length = 30; // Set object properties values
$obj->width = 20; // Set object properties values
 
// Read the object properties values again to show the change
echo $obj->length; // 0utput: 30
echo $obj->width; // 0utput: 20
 
// Call the object methods
echo $obj->getPerimeter(); // 0utput: 100
echo $obj->getArea(); // Output: 600

Make your functions flexible

Whenever adding a single item in session or any other object, you use the above function. When adding multiple items, will you create another function? So Just make the function flexible enough to take different kinds of parameters. Let's take an example:

function add_gift($item_id , $qty)
{
    $_SESSION['gift'][$item_id] = $qty;
}
 
add_gift( 'Phone' , 1 );

Above function used for the single gift add, now looks the example for single and more than one parameter:

function add_gift($item_id , $qty)
{
    if(!is_array($item_id))
    {
        $_SESSION['gift'][$item_id] = $qty;
    }
 
    else
    {
        foreach($item_id as $i_id => $qty)
        {
            $_SESSION['gift'][$i_id] = $qty;
        }
    }
}
 
add_gift( 'Phone' , 1 );
add_gift( array('Laptop' => 1 , 'Pen' => 2) );

Always correct character encoding for a MySQL connection

This is a big problem for beginners, ever faced a problem that Unicode/UTF-8 characters are stored in MySQL table correctly, PHP my admin also shows them correct, but when you fetch them and echo on your page they do not show up correctly. The secret is a MySQL connection collation.

Loading...
$host = 'localhost';
$username = 'root';
$password = 'password';
 
//Attempt to connect to database
$con = mysqli_connect($host , $username, $password);
         
//Check connection validity
if (!$con) 
{
    die ("Could not connect to the database host: ". mysqli_connect_error());
}
         
//Set the character set of the connection
if(!mysqli_set_charset ( $con , 'UTF8' ))
{
    die('mysqli_set_charset() failed');
}

Once you connect to the database, it's a good idea to set the connections characters. This is a must when you are working with multiple languages in your application.

Use of Prepared Statements for SQL injection attack

Always Use of Prepared Statements for SQL injection attacks instead of the normal SQL query. The first step in preventing a SQL injection attack is to establish which (if any) of your applications are vulnerable.

You need to implement prepared statements with Parameterized Queries. Let's take an example:

$cid = $_GET['cid'];
$get_prepare_query = db_prepare_query("select * from ".TABLE_CATEGORIES." where category_id = ?");
$get_prepare_query->bind_param('s', $cid);
$get_category_prepare_result = db_prepare_result($get_prepare_query);
$get_category_result = array_shift($get_category_prepare_result);
if(sizeof($get_category_result) == 0 ) tep_redirect(tep_create_url(''));
$category_id = $get_category_result['category_id'];

Use a switch instead of stringing If Statements

The useful PHP trick for Developers, use Switch instead of repetitive If conditions. The advantage of this, The code will execute faster thus performance is increased. The usage of Switch statements allows you to go beyond the use of if-else if-else chains.

if($color == 'yellow')
echo "The color is yellow";
if($color == 'black')
echo "The color is black";
if($color == 'red')
echo "The color is red";
if($color == 'pink')
echo "Color is pink";

the better way to do this like this with a switch:

Loading...
switch ($color ) {
case 'yellow' :
echo "The color is yellow" ;
break ;
case 'black' :
echo "The color is black" ;
break ;
case 'red' :
echo "The color is red" ;
break ;
case 'pink' :
echo "Color is pink" ;
break ;
}

Every large array work always should be with the chunk

We can optimize our long-lasting array work with the help of array chunk, In PHP we can able to slice an Array into small chunks. The array_chunk() function is a built-in function in PHP and used to split an array into parts or chunks of given size depending upon the parameters passed to the function.

A function of PHP for array chunk is:

array_chunk($array, $size)

The last chunk may contain the remaining data of the array, which may be less or equal to be the size.

$token_array = {'321321321s5d1s3d5a1sd',
'asda1s32d1a32s1d3a21d3a',
'4as3da4s2d13a21sd3da21d',
'5a6sd5as65da3s2d545sd4a',
'as4d534a3s5d4a3s5da35sd',
'a3sd4a35s4d35a4sd3a4ds3',
'45as4d3a54s3d5a43sd4ad3',
'43a5s4d35a4sd35a4s5a4s3',
'435a4sd35a4s3d5a4s3d5d4',
'3a5s4d35a4s3d5a4s3d543s',
'4a35s4d3a5s4d35a4s3d5d4',
'43as54d3a5s43d5a4s3d543'
.......};
foreach(array_chunk($token_array, 10) as $token){
  print_r($token)
  //manage your task
}

HTTP GET and POST Methods

HTTP works as a request-response protocol between a client and a server. A client submits an HTTP request to the server, then the server returns a response to the client. The response contains information about the requested content. Two types of methods:

  1. GET – Requests data from a specified resource.
  2. POST – Submits data to be processed to a specified resource.

Try to use always POST method always. like this:

Loading...
if(isset($_POST["name"])) {
 echo "Welcome ". $_POST['name'];
}

Check variable exists before use

Determine if a variable is set and is notNULL. Always check variable exists before use.

if(isset($_POST["name"])) {
 echo "Welcome ". $_POST['name'];
}

The isset () function is used to check whether a variable is set or not. The isset() function return false if given variable contains a NULL value.

Handle ternary operators

The best PHP tips and trick for good performance is to use ternary operators as an alternative to simple IF constructions. This would help your code to get lighter and can be nested without problems.

$phone = ( !empty ( $_POST['phone'] ) ? $_POST['phone'] : 9111111111 ) ;

These methods will save your time and less your code, make your habit with best practices.

Related posts

(3) Comments

  • User Pic

    Error in the second example "Create a class for repeated tasks"
    The rectangle object should be all $obj_rec or all $obj not both.
    Also if this is for beginners, you should say explicitly that you need to create Rectangle.php containing the Rectangle class.

  • User Pic

    Got to know a lot from the post. Thanks for sharing.

  • User Pic

    Really all points are basic, but important...

Write a comment