Monday, 17 July 2017

How to avoid Notices and warnings errors in PHP code.

While writing PHP code, we often get errors like warnings and notices.

To avoid them, following are some best practises:

1) Always check if a variable is set before using it.

For example:

$age = $_GET['age'];

Should be replaced by

$age = isset($_GET['age']) ? ($_GET['age'] : '';

Reference:

http://php.net/manual/en/function.isset.php

2) Always check if array is not empty before looping over it.

For example:

foreach ($arr as $elem) {
  // Your code.
}

Should be replaced by:

if (! empty($arr)) {
 foreach ($arr as $elem) {
   // Your code.
 }
}

Reference:

http://php.net/manual/en/function.empty.php

How to convert stdClass object to associative array in php

Use json_encode() and json_decode()

$arr = json_decode(json_encode($yourObject), TRUE);

json_decode() 's second parameter is set to TRUE.

Function definition:

mixed json_decode ( string $json [, bool $assoc = false [, int $depth  > = 512 [, int $options = 0 ]]] )

That will convert your object into an associative array.

Reference:

https://stackoverflow.com/questions/34428702/convert-stdclass-object-to-associative-array-in-php/34428735#34428735

How to solve Apache 2.4.3 (with XAMPP 1.8.1) not starting in windows

Problem:

Just got XAMPP 1.8.1 installed on my Windows 8 PC, this version includes packages mentioned below:

    Apache 2.4.3
    MySQL 5.5.27
    PHP 5.4.7
    phpMyAdmin 3.5.2.2
    FileZilla FTP Server 0.9.41
    Tomcat 7.0.30 (with mod_proxy_ajp as connector)
    Strawberry Perl 5.16.1.1 Portable
    XAMPP Control Panel 3.1.0 (from hackattack142)


When I launched and tried to start Apache, it gave following error:



    12:04:41 PM  [Apache] Attempting to start Apache app...
    12:04:41 PM  [Apache] Status change detected: running
    12:04:42 PM  [Apache] Status change detected: stopped
    12:04:42 PM  [Apache] Error: Apache shutdown unexpectedly.
    12:04:42 PM  [Apache] This may be due to a blocked port, missing dependencies,
    12:04:42 PM  [Apache] improper privileges, a crash, or a shutdown by another method.
    12:04:42 PM  [Apache] Check the "/xampp/apache/logs/error.log" file
    12:04:42 PM  [Apache] and the Windows Event Viewer for more clues

After that I checked error.log, it was empty so no help from there.


Solution:


This problem may occur due to apache not getting required port (default is `80`).

The port may be being used by other services.

For example: Skype also has default port `80`.

Installing Skype and Apache both on same machine will cause conflict and hence Apache will not start.

Either, you change Skype port or change Apache port as described in following steps:

Change the ports of Apache and it will work for you.
Go to httpd.conf

**How to change port for Apache:**

Search for:

ServerName localhost:80

Change it to:

ServerName localhost:81

Also Search For:
Listen 80

Change it to:
Listen 81

If you have created any virtual hosts, change the ports there also.
Then restart your apache.


Reference:

https://stackoverflow.com/a/18306621/1841760

Thursday, 21 July 2016

Show categories from database and show in a list.

How to display categories in a list:
Say, you have following categories on your site:
Administration, Sales, Production, Management, Inventory.
And you have to show it in a list.

You can show them simply by using PHP'a array functions.

implode().


Fetch categories from database and append to array.

while ($row = mysqli fetch array) {
 $categories[category id] = category name;
}

And while showing categories in ul li:
$categoriesHTML = '';
if (! empty($categories)) {
 $categoriesHTML .= '<ul>';
 foreach ($categories as $category) {
  $categoriesHTML .= '<li>' . $category . '</li>';
 }
 $categoriesHTML .= '<ul>';
}
echo $categoriesHTML;

OR, if you want to display as a comma separated string,'

just print it using implode().


echo (! empty($categories)) ? implode(', ', $categories) : '';

Sunday, 19 July 2015

PHP MySQL: Getting year, month, day, hour, minute and second from DATETIME field

We all need to extract day, month and year from date provided.

For this, we often explode() the provided input and then get the required elements from the array.

There is a strong option to this.

Use substr() to get sub-string.

In Database, DATE and DATETIME fields have specified lengths.

We can use substr() in that case.

Examples:

For DATETIME:
    $dt = '2015-07-20 11:23:56';
    echo "<br/> Date: " . $dt;
    echo "<br/> Year: " . substr($dt, 0, 4);
    echo "<br/> Month: " . substr($dt, 5, 2);
    echo "<br/> Day: " . substr($dt, 8, 2);
    echo "<br/> Hour: " . substr($dt, 11, 2);
    echo "<br/> Minute: " . substr($dt, 14, 2);
    echo "<br/> Second: " . substr($dt, 17, 2);

For DATE:
    $dt = '2015-07-20';
    echo "<br/> Date: " . $dt;
    echo "<br/> Year: " . substr($dt, 0, 4);
    echo "<br/> Month: " . substr($dt, 5, 2);
    echo "<br/> Day: " . substr($dt, 8, 2);

Thursday, 18 June 2015

PHP: Generate log messages and save to a custom file.

We all know that PHP save errors in php_errors.log file.

But, that file contains a lot of data.

If we want to log our application data, we need to save it to a custom location.

We can use two parameters in the error_log function to achieve this.

http://php.net/manual/en/function.error-log.php

We can do it using:

error_log(print_r($v, TRUE), 3, '/var/tmp/errors.log');

Where,

print_r($v, TRUE) : logs $v (array/string/object) to log file.
3: Put log message to custom log file specified in the third parameter.
'/var/tmp/errors.log': Custom log file (This path is for Linux, we can specify other depending upon OS).

OR, you can use file_put_contents()

file_put_contents('/var/tmp/e.log', print_r($v, true), FILE_APPEND);

Where:

'/var/tmp/errors.log': Custom log file (This path is for Linux, we can specify other depending upon OS).
print_r($v, TRUE) : logs $v (array/string/object) to log file.
FILE_APPEND: Constant parameter specifying whether to append to the file if it exists, if file does not exist, new file will be created.

How to check the version of Yii.

To check version of Yii we are using, use the following code:

Yii::getVersion()

Parenting tips to inculcate learning habits in your kid

Parenting tips to inculcate learning habits in your kid Tip #1) Children do not learn things, they emitate. So, try to do things by yours...