Friday 3 October 2014

Drupal PHP Query Connection

$DB_NAME = DB_START_NAME . $clinic_id;
    dpr($DB_NAME);
    $database_info = array(
        'host' => HOST_NAME,
        'database' => $DB_NAME,
        'username' => HOSTUSER,
        'password' => HOSTPASS,
        'driver' => 'mysql',
    );

    Database::addConnectionInfo('flat_db', 'default', $database_info);
    $key = 'flat_db';
    $custom_db = Database::getConnection($DB_NAME, $key);
    $sql_query = "SELECT * FROM sc_patient_appointments LIMIT 1";  
    $result = $custom_db->query($sql_query);
       foreach ($result as $row) {
        //$reaged = (array) $row; // Standard object to array  
        dpr($row);
    }

Sunday 31 August 2014

Php String Split to Array

$str = 'one,two,three,four';
$arr=explode(",",$str);
dpr($arr);

--------Result 

Array
(
    [0] => one
    [1] => two
    [2] => three
    [3] => four
)

Monday 11 August 2014

drupal mysql insert statement

$id = db_insert('pms_link_master')
      ->fields(array(
          'NODE_ID' => '1',
          'PMS_ID' => '2',
          'CLINIC_ID' => '415',
          'MASTER_TYPE' => 'location'
  ))
  ->execute();

drupal custom mysql statement

 $sql_query = db_query("select * from pms_link_master");
  echo "total rows ".$sql_query->rowCount();

    $sql_array = array();
    foreach ($sql_query as $row) {
        $reaged = (array) $row; // Standard object to array    
        $sql_array[] = $reaged;
    }
dpr($sql_array);

Friday 4 July 2014

PHP Read Folder Files



  $files = glob($dir . '*.csv');

foreach ($files as $x => $x_filepath) {
        // get file path
        $filePath = $x_filepath;
        // get file name
        $file_NAME = basename($filePath, ".csv");
}

PHP Read CSV file and store in array

function fun_readCSV($csvFile) {
    if (!file_exists($csvFile) || !is_readable($csvFile)) {
        fun_logMessage($messageID = '', $message = 'File Not Found', $mstType = 'Developer', $fieldName = '', $rowID = '');
        return FALSE;
    }
    $file_name = basename($csvFile);  // Show File Name
    echo ' File Size '.filesize($csvFile);
    $file_handle = fopen($csvFile, 'r');
    while (!feof($file_handle)) {
        $line_of_text[] = fgetcsv($file_handle, 1024);
    }
    fclose($file_handle);
    $line_of_text = array_unique($line_of_text, SORT_REGULAR);   
    print array2table($line_of_text);
    return $line_of_text;
}

PHP Drupal View to Array

function fun_View_to_Array($clinic_id, $fileType) {
    $view_get_field_details = views_get_view_result("pms_details", "page_4", $clinic_id, $fileType);
    //show_array($view_get_field_details);
    $array_field_list = array();
    if ($view_get_field_details) {
        foreach ($view_get_field_details as $fields) {
            $field_info = array();
            //print $fields->field_field_pms_field_validation_id[0]['raw']['target_id'];             

            $field_info['field_nid'] = $fields->nid;
            $field_info['field_name'] = $fields->node_title;
            $field_info['file_name'] = $fields->field_field_pms_file_name[0]['raw']['value'];
            $field_info['field_length'] = $fields->field_field_pms_field_length[0]['raw']['value'];
            $field_info['field_sequence'] = $fields->field_field_pms_field_sequence[0]['raw']['value'];
            $field_info['validation_nid'] = $fields->field_field_pms_field_validation_id[0]['raw']['target_id'];
            $field_info['clinic_id'] = $fields->field_field_pms_field_clinic_id[0]['raw']['target_id'];
            $field_info['Validation_message'] = $fields->field_field_pms_validation_message[0]['raw']['value'];
            $field_info['Validation_id'] = $fields->field_field_pms_validation_id[0]['raw']['value'];
            $array_field_list[] = $field_info;
        }
    }
    //print array2table($array_field_list);
    //show_array(array_filter($array_field_list, "Search_Function"));
    return $array_field_list;
}

Thursday 3 July 2014

array search

function findWhere($array, $matching) {
    foreach ($array as $item) {
        $is_match = true;
        foreach ($matching as $key => $value) {

            if (is_object($item)) {
                if (! isset($item->$key)) {
                    $is_match = false;
                    break;
                }
            } else {
                if (! isset($item[$key])) {
                    $is_match = false;
                    break;
                }
            }

            if (is_object($item)) {
                if ($item->$key != $value) {
                    $is_match = false;
                    break;
                }
            } else {
                if ($item[$key] != $value) {
                    $is_match = false;
                    break;
                } 
            }
        }

        if ($is_match) {
            return $item;   
        }
    }

    return false;
}
Example:
$cars = array(
    array('id' => 1, 'name' => 'Toyota'),
    array('id' => 2, 'name' => 'Ford')
);

$car = findWhere($cars, array('id' => 1));
or

$car = findWhere($cars, array(
    'id' => 1,
    'name' => 'Toyota'
));

PHP DateTime Validation

  if (DateTime_Validation($text, $format = 'YmdHi') == 1) {       
        return 1; // False
    }
    return 0; // True

function DateTime_Validation($date, $format = 'YmdHi') {
    $d = DateTime::createFromFormat($format, $date);
    $return_type = $d && $d->format($format) == $date;
    if ($return_type == 1) {
        return 0;
    } else {
        return 1;
    }
}

PHP Multidimensional Array Search by Column


$result_array = (search($array_list, 'column_name', 'Value'));

function search($array, $key, $value) {
    $results = array();

    if (is_array($array)) {
        if (isset($array[$key]) && $array[$key] == $value) {
            $results[] = $array;
        }

        foreach ($array as $subarray) {
            $results = array_merge($results, search($subarray, $key, $value));
        }
    }

    return $results;
}

PHP Array To HTML Table Conversion

print array2table($array);     

function array2table($array, $recursive = false, $null = ' ')
{
    // Sanity check
    if (empty($array) || !is_array($array)) {
        return false;
    }

    if (!isset($array[0]) || !is_array($array[0])) {
        $array = array($array);
    }

    // Start the table
    
    $table = '<table class="table table-bordered table-striped dataTable">';

    // The header
    $table .= "\t<tr>";
    // Take the keys from the first row as the headings
    foreach (array_keys($array[0]) as $heading) {
        $table .= '<th>' . $heading . '</th>';
    }
    $table .= "</tr>\n";

    // The body
    foreach ($array as $row) {
        $table .= "\t<tr>" ;
        foreach ($row as $cell) {
            $table .= '<td>';

            // Cast objects
            if (is_object($cell)) { $cell = (array) $cell; }
             
            if ($recursive === true && is_array($cell) && !empty($cell)) {
                // Recursive mode
                $table .= "\n" . array2table($cell, true, true) . "\n";
            } else {
                $table .= (strlen($cell) > 0) ?
                    htmlspecialchars((string) $cell) :
                    $null;
            }

            $table .= '</td>';
        }

        $table .= "</tr>\n";
    }

    $table .= '</table>';
    return $table;
}

Monday 23 June 2014

PHP String Functions

There are three main ways to define strings in PHP. We have:
  • Characters enclosed in double quotes.
  • Characters enclosed in single quotes.
  • Characters or lines of characters enclosed by heredoc symbols
Double Quotes
Double quotes are useful when you have a PHP variable you want to embed within the string, since when the PHP runs, it will use interpolation to grab the actual value of that variable.
Single Quotes
Some people find it easier to leave their variables out of strings and let them be more hard coded sort to speak. Use single quotes for that.
Heredoc Syntax
Note: You don’t have to use EOD as your delimiter, you can use anything you like as long as they are the same!

Most Popular PHP String Functions

1. substr()

The substr() function helps you to access a substring between given start and end points of a string. It can be useful when you need to get at parts of fixed format strings.
The substr() function prototype is as follows:
The return value is a substring copied from within string.
When you call the function with a positive number for start (only), you will get the string from the start position to the end of the string.
String position starts from 0, just like arrays.
When you call substr() with a negative start (only), you will get the string from the end of the string minus start characters to the end of the string.
The length parameter can be used to specify either a number of characters to return if it is positive, or the end character of the return sequence if it is negative.
5 signifies the starting character point (B) and -13 determines the ending point (count 13 places backwards starting from the end of the string).
Learn more about substr() at http://us3.php.net/substr

2. strlen()

Next up we have the popular strlen() function for checking the length of a string. If you pass it a string,strlen() will return its length.
Often times this function is used for validating input data or making sure a string variable has a value.
Learn more about strlen() at http://us3.php.net/strlen

3. str_replace()

Find and replace functionality is super useful with strings. You can use find and replace for almost anything your imagination can think of.
The most commonly used string function for replacement is str_replace(). It has the following prototype:
str_replace() replaces all the instances of needle in haystack with new_needle and returns the new version of the haystack.The optional fourth parameter contains the number of replacements made.
A really awesome feature of str_replace() is the ability to pass an array to both the search terms and replace terms, as well as an array of strings to apply the rules to!
Learn more about str_replace() at http://php.net/manual/en/function.str-replace.php

4. trim()

The first step in tidying up data is to trim any excess whitespace from the string. This is a good idea to prepare for a database insert or string comparison.
The trim() function strips whitespace from the start and end of a string and returns the resulting string. The characters it strips by default are newlines and carriage returns (\n and \r), horizontal and vertical tabs (\t and \x0B), end-of-string characters (\0), and spaces. You can also pass it a second parameter containing a list of characters to strip instead of this default list. Depending on your particular purpose, you might like to use theltrim() or rtrim() functions instead which perform the same operation, but you choose which side of the string to affect.
Here we remove some literal junk from the beginning and end of our string:
Learn more about trim() at http://us2.php.net/manual/en/function.trim.php

5. strpos()

The function strpos() operates in a similar fashion to strstr(), except, instead of returning a substring, it returns the numerical position of a needle within a haystack.
The strpos() function has the following prototype:
The integer returned is the position of the first occurrence of the needle within the haystack. The first character is in position 0 just like arrays.
We can see by running the following code that our exclamation point is at position 13.
This function accepts a single character as the needle, but it can accept a string of any length. The optional offset parameter determines the point within the haystack to start searching.
This code echoes the value 11 to the browser because PHP has started looking for the character ‘m’ at position 3.
In any of these cases, if the needle is not in the string, strpos() will return false. To avoid strange behavior you can use the === operator to test return values:
Learn more about strpos() at http://us2.php.net/strpos

6. strtolower()

Very often in PHP we need to compare strings or correct capitalization when people SHOUT or do odd things. In order to compare strings, you want to make sure they are the same case. We can use strtolower() for this purpose. We’ll use a function created with strtolower() to calm down an angry person.
Learn more about strtolower() at http://us3.php.net/strtolower

7. strtoupper()

strtoupper() is also quite popular for many of the reasons listed above, in reverse, meaning take lowercase or a mixed case string and set it to all upper case. We’ll change things up and create a wake up function to get our workers going in the morning.
Learn more about strtoupper() at http://us3.php.net/strtoupper

8. is_string()

is_string() is used to check if a value is a string. Let’s take a look at this within an if() statement to take an action on strings in one way and non-strings in another. is_string() returns true or false.
Learn more about is_string() at http://us2.php.net/is_string

9. strstr()

Last but not least we have the strstr() function. The function strstr() can be used to find a string or character match within a longer string. This function can be used to find a string inside a string, including finding a string containing only a single character.
The function prototype for strstr() is as follows:
You pass strstr() a haystack to be searched and a needle to be found. If an exact match of the needle is found, the strstr() function returns the haystack from the needle onward. If it does not find the needle, it will return false. If the needle occurs more than once, the returned string will begin from the first occurrence of the needle.
As an example, let’s say we have a submission form for people to submit their website, but we would like it in a certain format. We can use strstr() to check for a string within a string to help us here: