Skip to main content

Other useful things I sometime use but always forgot

 🐘Useful PHP functions


One line year array

// will get the past 3 year including current year. eg: 2021,2022,2023

for ($i=-2; $i <= 0 ; $i++) $data['year'][date('Y')+$i] = date('Y')+$i;


Unset attribute in array of array object

$body_list[$count] = array(

            'attr' => array(

                '1' => 'one',

                '2' => 'two',

            ),

            'data' => (object) array(

                '3' => 'three',

                '4' => 'four',

            )

        );


unset($body_list[$count]['data’]->{‘3’}); // will remove attribute ‘three’


Merge/combine array with duplicate keys while preserving the values

// use this inside loops where + wont work between each iteration

foreach ($array2 as $value) $array1[] = $value; 

return $array1;


Divide string in two parts based on certain lengths

private function _divide_string($text, $length) {

        $words          = explode(" ", $text);

        $top_text       = $bottom_text = "";

        $total_length   = 0;


        foreach ($words as $word) {

            $word_length = strlen($word) + 1;

            if ($total_length + $word_length <= $length) {

                $top_text .= $word . " ";

                $total_length += $word_length;

            } else {

                $bottom_text .= $word . " ";

            }

        }


        return [trim($top_text), trim($bottom_text)];

    }


List out all files in a folder into a html table for easy copying into excel/spreadsheets

public function spout_nonsense()

    {

        $string = shell_exec("ls application/controllers | paste -sd ',' -");

        $controller_list = explode(',', $string);


        echo '<html><head></head><body><table><tbody>';

        foreach ($controller_list as $file_name) {

            echo '<tr><td>'.str_replace('.php', '', $file_name).'</td></tr>';

        }

        echo '</tbody></table></body></html>';

    }


Export current db into another db as backup

/**

     * Export current db into another db as backup

     * @param String $api_key

     */

    public function backup_yesterday($api_key = NULL)

    {

        if ($api_key != SMAP_API_KEY) exit('No access');


        $start_time = time();


        $user   = $_SERVER['DB_USER'];

        $pass   = $_SERVER['DB_PASSWORD'];

        $db     = $_SERVER['DB_NAME'];


        $backup_db  = 'smap_backup';

        $file_path  = PATH_IMAGE . 'temp_backup/yesterday.sql.gz';

        $mysql_path = '/Applications/MAMP/Library/bin'; // for MAMP only, change this to suit your local machine


        if (!file_exists(dirname($file_path))) { // create folder if not exist

            mkdir(dirname($file_path), 0755, TRUE);

        }

        file_put_contents($file_path, ''); // create temporary file


        // export db into temporary file

        $export_command = "$mysql_path/mysqldump --single-transaction --quick -u $user -p'$pass' $db | gzip > $file_path";

        exec($export_command, $output, $result);


        $messages = '';

        if ($result == 0) {

            $messages .= "DB '$db' exported to $file_path \n\n";


            // import db

            $import_command = "gunzip < $file_path | $mysql_path/mysql -u $user -p'$pass' $backup_db";

            exec($import_command, $output, $result);


            if ($result == 0) {

                $messages .= "DB '$backup_db' imported from $file_path \n\n";

            } else {

                $messages .= "Error importing DB \n\n";

            }

        } else {

            $messages .= "Error exporting DB \n\n";

        }


        // delete temporary file

        if (unlink($file_path)) {

            $messages .= "Deleted $file_path \n\n";

        } else {

            $messages .= "Error deleting file \n\n";

        }


        $messages .= 'Runtime: ' . (time() - $start_time) . ' seconds';


        echo nl2br($messages);

    }


📝 Useful mysql scripts 


Error something something group by

SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));


List all tables inside a database into a string

USE db_name;

SELECT GROUP_CONCAT(table_name SEPARATOR ', ') AS tables FROM information_schema.tables WHERE table_schema = ‘db_name’;


Sanitise data in table

UPDATE table_name

SET email = NULL, phone = NULL 

WHERE email NOT LIKE '%@getnada.com%';


Useful js funcs


Format currency strings like ’20,000.00’ into floats ’20000.00’

    function stringToFloat(str) {

        return parseFloat(str.replace(/,/g, ''));

    }




 


Comments

Popular posts from this blog

🗑️ Clear storage Mac OS

  🗑️ Clear storage Mac OS 1: Clear system cache: Go to Finder > Go > Go to Folder, then type in "~/Library/Caches" and hit enter. Select all the folders inside the Caches folder and delete them. 2: Clear system logs: Go to Finder > Go > Go to Folder, then type in "/var/log" and hit enter. Select all the files inside the Log folder and delete them. 3: Remove unused language files: Go to Finder > Go > Go to Folder, then type in "/Library/Languages" and hit enter. Delete all the language folders you don't need. 4: Uninstall unused apps: Go to the Applications folder and delete the apps you don't use. 5: Clean up system files: Use a system cleaning tool like CleanMyMac X to scan and remove unnecessary system files. 6: If you have npm installed, clear the caches once in a while with ‘sudo npm cache clean --force’ 7: If you have ionic projects, open the ‘.angular’ folder and delete the ‘cache’ folder inside it.

Turning AIs Into Cavemen Is Actually A Good Idea

    Token limits have been the number 1 problem of vibecoding. Aside from high usage, vague prompting and inefficient context management are two key causes that contribute to this problem. Tokens are counted from two things, the user’s input and agent’s output. You can have the best prompt in the world, but if your AI puke a Shakespearean essay for each response, your token will reach its limit faster. Similarly, if your prompt is too long, your token usage will also skyrocket. Prompting Prompting seems easy enough, but the reality is, if you want quality output, the input must be of similar quality. Here are some tips you can try to achieve a better, token-efficient prompt. Stick to English language only Certain languages may use higher tokens. Switching between languages might not be a good idea. Sure you can control your input prompt, but the output may use more tokens. Extremely short input Do not use ‘please’ or ‘thank you’. Get rid of filler words. Straight to the point....

Setup existing IONIC project in local

Setup existing IONIC project in local  Steps: clone git repo install ionic -  npm install -g @ionic/cli masuk folder repo project install npm dependencies -  npm install run ionic project -  ionic serve buka android studio / xcode -  ionic cap open $var  - $var = ‘android’ atau ‘ios’. ada dua je option, replace $var dgn dua option tu sync changes vscode & dkt android studio / xcode -  ionic cap sync good luck Common issues: dependency conflict check https://www.npmpeer.dev/ utk tengok version yg compatible try naikkan/turunkan version dependency yg keluar dkt error. tembak je sampai hilang error g radle issue try upgrade gradle. kalau tak boleh, try remove folder android & build semula e rror cocoapod make sure install xcode make sure install cocoapod error java  home not found utk mac, buka ~/.zshrc & masukkan chang es dkt VSC tak masuk android studio / xcode try ionic cap sync try quit & buka semula cordo va.variables.gradle no...