Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@git-e-001
Forked from eliyas5044/MySQL.md
Created May 23, 2021 06:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save git-e-001/bac6c303de039febef81b6557666575e to your computer and use it in GitHub Desktop.
Save git-e-001/bac6c303de039febef81b6557666575e to your computer and use it in GitHub Desktop.
MySQL Commands for Laravel

MySQL CLI

To login into mysql, enter db_password

mysql -u db_user -p

Create database

CREATE DATABASE db_name;

Drop database

DROP DATABASE db_name;

Drop table

DROP TABLE IF EXISTS db_name.table_name;

Drop all tables

echo "db_name"| xargs -I{} sh -c "mysql -Nse 'show tables' {}| xargs -I[] mysql -e 'SET FOREIGN_KEY_CHECKS=0; drop table []' {}"

Create user in MySQL 5.7

CREATE USER 'db_user'@'localhost' IDENTIFIED WITH mysql_native_password BY 'db_password';

Grant permission

GRANT ALL ON db_name.* TO 'db_user'@'localhost' IDENTIFIED BY 'db_password' WITH GRANT OPTION;

Create user in MySQL 8

CREATE USER 'db_user'@'%' IDENTIFIED WITH mysql_native_password BY 'db_password';

Grant permission

GRANT ALL ON db_name.* TO 'db_user'@'%';

Reset root password

UPDATE mysql.user SET Password=PASSWORD('password') WHERE User='root';

Reload grant

FLUSH PRIVILEGES;

mysqldump database to export as gzip

mysqldump -u db_user -p db_name | gzip > ~/db.sql.gz

mysqldump database to export as sql

mysqldump -u db_user -p db_name > ~/db.sql

mysqldump database to export as gzip from remote database

mysqldump -P 3306 -h ip_address -u db_user -p db_name | gzip > ~/db.sql.gz

Import sql format to MySQL

mysql -u db_user -p db_name < ~/db.sql

Import gzip format to MySQL

zcat ~/db.sql.gz | mysql -u db_user -p db_name

Create SSH tunnel to connect remote MySQL

ssh -fNg -L 3307:127.0.0.1:3306 user_name@ip_address

// next connect MySQL in command line
mysql -h 127.0.0.1 -P 3307 -u db_user -p db_name

// for Laravel, change .env file
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3307
DB_DATABASE=db_name
DB_USERNAME=db_user
DB_PASSWORD=db_password
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment