Pages

Thursday, September 14, 2023

show time in human difference time in custom php function

function time_elapsed_string($datetime, $full = false) {

            $now = new DateTime;

            $ago = new DateTime($datetime);

            $diff = $now->diff($ago);

            $diff->w = floor($diff->d / 7);
            $diff->d -= $diff->w * 7;

            $string = array(

                'y' => 'year',

                'm' => 'month',

                'w' => 'week',

                'd' => 'day',

                'h' => 'hour',

                'i' => 'minute',

                's' => 'second',

            );

            foreach ($string as $k => &$v) {

                if ($diff->$k) {

                    $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');

                } else {

                    unset($string[$k]);

                }

            }

            if (!$full) $string = array_slice($string, 0, 1);

            return $string ? implode(', ', $string) . ' ago' : 'just now';

        }

// show time in human difference time in custom php function

<?php echo  time_elapsed_string($key['date_created'], true); ?>

Tuesday, May 9, 2023

How to exclude databases while importing a MySQL backup file

Introduction:

If you need to import a MySQL backup file that contains multiple databases, you may want to exclude some of the existing databases from being overwritten. In this tutorial, we will show you how to exclude specific databases while importing a MySQL backup file using a bash script.

Prerequisites:

Basic knowledge of bash scripting

Access to a command-line interface

A MySQL database backup file (.sql extension)

Steps:

1. Create a new bash script file and open it using a text editor of your choice.

2. Add the following code to the file:

bash
#!/bin/bash 
echo "Enter MySQL username: "
read -s USERNAME
echo "Enter MySQL password: "
read -s PASSWORD
echo "Enter MySQL host (default: localhost): "
read HOST 
if [ -z "$HOST" ]; 
  then HOST="localhost"
fi 
echo "Enter path to backup file (e.g. /path/to/backup.sql): "
read BACKUP_PATH
if [ ! -f "$BACKUP_PATH" ];
then
  echo "File not found: $BACKUP_PATH"
  exit 1
fi 
 DATABASES=$(mysql --user="$USERNAME" --password="$PASSWORD" --host="$HOST" -e "SHOW DATABASES;" | grep -Ev "(Database|information_schema|mysql|mytinerycms|performance_schema|sys)")

for
db in $DATABASES
do
 DB_ARGS+=(
"--database" "$db")
done 
 mysql --user="$USERNAME" --password="$PASSWORD" --host="$HOST" "${DB_ARGS[@]}" < "$BACKUP_PATH"

3. Save the file with a name such as mysql-import.sh.
4. Open a terminal or command prompt and navigate to the directory where you saved the script.
5. Make the script executable by running the following command:

chmod +x mysql-import.sh

7. When prompted, enter your MySQL username and password. If your MySQL server is running on a different host than localhost, enter the hostname as well.
8. Enter the path to the backup file when prompted.
9. The script will exclude the following databases from the import: information_schema, mysql, mytinerycms, performance_schema, sys. All other databases will be included.
10. The script will import the backup file to the specified MySQL server.

Conclusion:
In this tutorial, we showed you how to exclude specific databases while importing a MySQL backup file using a bash script. By modifying the script, you can exclude any database from the import by adding its name to the exclusion list. This is a simple and effective way to prevent overwriting existing databases while importing backups.








Saturday, December 31, 2022

Laravel .htacess for setting root as working directory

 <IfModule mod_rewrite.c>

       RewriteEngine On

       RewriteRule ^(.*)$ public/$1 [L]

    </IfModule>


React app build .htaccess for live server

 <IfModule mod_rewrite.c>


  RewriteEngine On

  RewriteBase /

  RewriteRule ^index\.html$ - [L]

  RewriteCond %{REQUEST_FILENAME} !-f

  RewriteCond %{REQUEST_FILENAME} !-d

  RewriteCond %{REQUEST_FILENAME} !-l

  RewriteRule . /index.html [L]


</IfModule>

Friday, November 5, 2021

Update User password in firebase and update data in firebase table

<script src="https://www.gstatic.com/firebasejs/8.4.1/firebase-app.js"></script>

<!--   TODO: Add SDKs for Firebase products that you want to use https://firebase.google.com/docs/web/setup#available-libraries   -->

<script src="https://www.gstatic.com/firebasejs/8.4.1/firebase-analytics.js"></script>

<script src="https://www.gstatic.com/firebasejs/8.4.1/firebase-auth.js"></script>

<script src="https://www.gstatic.com/firebasejs/8.4.1/firebase-database.js"></script>


<scipt>

const firebaseConfig = {

    apiKey: "APIKEY",

    authDomain: "my-project-ID.firebaseapp.com",

    projectId: "my-project-ID",

    storageBucket: "my-project-ID.appspot.com",

    messagingSenderId: "messagingSenderID",

    appId: "1:APIID",

    measurementId: "MEASUREMENT-ID",

    databaseURL: "https://my-project-ID-default-rtdb.firebaseio.com/",

  };

</scipt>


<script>

var New_Password = "test123";

const user = firebase.auth().currentUser;

              user.updatePassword(New_Password).then(() => {

                alert("successfully updated password");

              }).catch(function (error) {

                alert("failed"+ error.message);

              }); 

/********** UPDATE USER DATA ***********/

$("#updateUserData").on('click', function (e) {

  e.preventDefault();

  var firstName = $("#First-Name-Account").val();

  var lastName = $("#Last-Name-Account").val();

  var emailAddress = $("#Email-Account").val();

  var phoneNumber = $("#Phone-Account").val();

  

  let userRef = database.ref('users/' + userId);

  userRef.child(userId).set({

    "firstName": firstName,

    'lastName': lastName,

    'emailAddress': emailAddress,

    'phoneNumber': phoneNumber

  }).then(function() {

    errors = "Profile updated successfully";

    alert(errors);

    // Data saved successfully!

  })

  .catch(function(error) {

    // The write failed...

    errors = error.message;

    alert(errors);

  });

});

</script>

Friday, July 16, 2021

Find and delete all files from current and recursive directory in Linux

https://www.cyberciti.biz/faq/linux-unix-how-to-find-and-remove-files/

find . -type f -name "*youfilename" -print0 | xargs -I {} -0 rm -v "{}"

 

find . -type f -name "*.zip" -print0 | xargs -I {} -0 rm -v "{}"

Sunday, July 11, 2021

UBuntu Database Error: Access denied for user 'root@localhost' (using password:NO)

 
https://stackoverflow.com/questions/2995054/access-denied-for-user-rootlocalhost-using-passwordno

[root ~]# mysql -u root
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password:NO)

sudo mkdir /var/run/mysqld
sudo chown mysql: /var/run/mysqld

sudo mysqld_safe --skip-grant-tables --skip-networking &



1. Stop the service/daemon of mysql running

    [root ~]# service mysql stop   
    mysql stop/waiting

2. Start mysql without any privileges using the following option; This option is used to boot up and do not use the privilege system of MySQL.
    [root ~]# mysqld_safe --skip-grant-tables &

3. enter the mysql command prompt
    [root ~]# mysql -u root
    mysql>

4. Fix the permission setting of the root user ;
    mysql> use mysql;
    Database changed
    mysql> select * from  user;
    Empty set (0.00 sec)
    mysql> truncate table user;
    Query OK, 0 rows affected (0.00 sec)
    mysql> flush privileges;
    Query OK, 0 rows affected (0.01 sec)
    mysql> grant all privileges on *.* to root@localhost identified by 'YourNewPassword' with grant option;
    Query OK, 0 rows affected (0.01 sec)

*if you don`t want any password or rather an empty password
    
    mysql> grant all privileges on *.* to root@localhost identified by '' with grant option;
    Query OK, 0 rows affected (0.01 sec)*
    mysql> flush privileges;
    Query OK, 0 rows affected (0.00 sec)

Confirm the results:
    mysql> select host, user from user;
    +-----------+------+
    | host      | user |
    +-----------+------+
    | localhost | root |
    +-----------+------+
    1 row in set (0.00 sec)

5. Exit the shell and restart mysql in normal mode.
    mysql> quit;
    [root ~]# kill -KILL [PID of mysqld_safe]
    [root ~]# kill -KILL [PID of mysqld]
    [root ~]# service mysql start

6. Now you can successfully login as root user with the password you set
    [root ~]# mysql -u root -pYourNewPassword
     mysql>