Sunday, March 31, 2013

Create your own Error Handler in PHP.

Hello friends,

Yesterday, one of my friend told me that he doesn't like the notice and warning shown in PHP. So I read over Internet and here's what I came up with.

So today in Developer's Blog I will tell you the way to create our own Error handler in PHP. By doing this, we can get rid of default errors shown in PHP.

You can create your own Error handler in PHP like this :

function myErrorHandler($errno, $errstr, $errfile, $errline)
{
    if(!(error_reporting() & $errno)) {
            // This error code is not included in error_reporting
            return;
    }

    switch($errno) {
            case E_USER_ERROR:
            echo "<b>My ERROR</b> [$errno] $errstr<br />\n";
            echo "  Fatal error on line $errline in file $errfile";
            echo ", PHP " . PHP_VERSION . " (" . PHP_OS . ")<br />\n";
            echo "Aborting...<br />\n";
            exit(1);
            break;

            case E_USER_WARNING:
            echo "<b>My WARNING</b> [$errno] $errstr<br />\n";
            break;

            case E_USER_NOTICE:
            echo "<b>My NOTICE</b> [$errno] $errstr<br />\n";
            break;

            default:
            echo "Unknown error type: [$errno] $errstr<br />\n";
            break;
        }

        /* Don't execute PHP internal error handler */
        return true;
    }

    // function to test the error handling
    function scale_by_log($vect, $scale)
    {
        if(!is_numeric($scale) || $scale <= 0) {
            trigger_error("log(x) for x <= 0 is undefined, you used: scale = $scale", E_USER_ERROR);
        }

        if(!is_array($vect)) {
            trigger_error("Incorrect input vector, array of values expected", E_USER_WARNING);
            return null;
        }

        $temp = array();
        foreach($vect as $pos => $value) {
            if (!is_numeric($value)) {
                trigger_error("Value at position $pos is not a number, using 0 (zero)", E_USER_NOTICE);
                $value = 0;
            }
            $temp[$pos] = log($scale) * $value;
        }

        return $temp;
    }

    // set to the user defined error handler
    $old_error_handler = set_error_handler("myErrorHandler");

E.g.,

$a = array(2, 3, "foo", 5.5, 43.3, 21.11);
$b = scale_by_log($a, M_PI);

Output :

My NOTICE [1024] Value at position 2 is not a number, using 0 (zero)

So this was the way you can create your own error handler in PHP.

Download Source Files

I hope this will help you and you will like it.

Don't forget to leave your comments.


Thank you

Ravinder


INSERT, UPDATE, DELETE And SELECT Operations in a Magento Module

Hello friends,

Today in Developer's Blog I will tell you the way to perform INSERT, UPDATE, DELETE And SELECT Operations in a Magento Module.

Suppose, I have a module named mynews
Here follows the code to select, insert, update, and delete data from the news table.

INSERT DATA : 

$data contains array of data to be inserted. The key of the array should be the database table’s field name and the value should be the value to be inserted.

$data = array('title'=>'hello there','content'=>'how are you? i am fine over here.','status'=>1);

$model = Mage::getModel('mynews/mynews')->setData($data);

try{
    $insertId = $model->save()->getId();
    echo "Data successfully inserted. Insert ID: ".$insertId;
}catch (Exception $e){
    echo $e->getMessage();   
}

SELECT DATA :

$item->getData() prints array of data from news table.
$item->getTitle() prints the only the title field.

Similarly, to print content, we need to write $item->getContent().

$model = Mage::getModel('mynews/mynews');

$collection = $model->getCollection();

foreach($collection as $item){
    print_r($item->getData());
    print_r($item->getTitle());
}

UPDATE DATA :

$id is the database table row id to be updated.
$data contains array of data to be updated. The key of the array should be the database table’s field name and the value should be the value to be updated.

$id = $this->getRequest()->getParam('id');

$data = array('title'=>'hello test','content'=>'test how are you?','status'=>0);

$model = Mage::getModel('mynews/mynews')->load($id)
->addData($data);

try{
    $model->setId($id)->save();
    echo "Data updated successfully.";
}catch(Exception $e){
    echo $e->getMessage(); 
}

DELETE DATA :

$id is the database table row id to be deleted.

$id = $this->getRequest()->getParam('id');

$model = Mage::getModel('mynews/mynews');

try{
    $model->setId($id)->delete();
    echo "Data deleted successfully.";
}catch(Exception $e){
    echo $e->getMessage(); 
}

In this way you can perform select, insert, update and delete in your custom module and in custom code in Magento as well.

I hope this will help you and you will like it.

Don't forget to leave your comments.


Thank you

Ravinder

Saturday, March 30, 2013

PHP Function to calculate age from date of birth

Hello friends,

In almost every project in which we let the user register on our website, we definitely want date of birth (DOB) and age of the user. So I thought about creating a function which will calculate age from date of birth, so we won't have to take age from the user and it will save us some coding and time. 

So today in Developer's Blog we will learn that how to calculate age from date of birth.

function calculateAge($dob) 
{
    //calculate years of age (input string: YYYY-MM-DD)
    list($year, $month, $day) = explode("-", $dob);

    $year_diff  = date("Y") - $year;
    $month_diff = date("m") - $month;
    $day_diff   = date("d") - $day;

    if ($day_diff < 0 || $month_diff < 0)
        $year_diff--;

    return $year_diff;
}

I hope this will help you and you will like it.

Don't forget to leave your comments.

Thank you
Ravinder

Friday, March 29, 2013

PHP Function to addslashes to an array

Hello friends,

Few days before I posted the function which stripslashes from an array. Today I thought about creating a function which addslashes to an array. so I created this function and want to share it with you guys as well. So I am posting this code to addslashes to an array.

We all know that there is a function to addslashes to an string in PHP but the function which I am posting
 in Developer's Blog right now will addslashes to an array.


function addSlashesArray($array
{
    foreach ($array as $key => $val) 
    {
        if (is_array($val))
        {
            $array[$key] = addSlashesArray($val);
        }
        else
        {
            $array[$key] = addslashes($val);
        }
    }
    return $array;
}

I hope this will help you and you will like it.

Don't forget to leave your comments.

Thank you
Ravinder

Tuesday, March 26, 2013

PHP Function to stripslashes from an array

Hello friends,

Today I was working and was using stripslashes a lot from all the variables. So I thought about creating a function which can stripslashes from the whole array, so I created this function and want to share it with you guys as well. So I am posting this code to stripslashes from an array.

We all know that there is a function to stripslashes from an string in PHP but the function which I am posting in Developer's Blog right now will stripslashes from an array.

function stripSlashesArray($array)
{
    foreach($array as $key => $val)
    {
        if (is_array($val))
        {
             $array[$key] = stripSlashesArray($val);
        }
        else
        {
             $array[$key] = stripslashes($val);
        }
    }
    return $array;
}


I hope this will help you and you will like it.

Don't forget to leave your comments.

Thank you
Ravinder