Skip to content

Instantly share code, notes, and snippets.

@taz77
Forked from zaiddabaeen/exportMySQLUsersPDO.php
Last active November 3, 2019 15:46
Show Gist options
  • Save taz77/4a5976f9899a4a21ce70708a65f33b2d to your computer and use it in GitHub Desktop.
Save taz77/4a5976f9899a4a21ce70708a65f33b2d to your computer and use it in GitHub Desktop.
Exports MySQL Users and Privileges using PDO
<?php
# vim:sts=4:sw=4
/*
* Feel free to improve it.
* Original by Janich: https://gist.github.com/janich/6121771
*
* @requires PHP 5.3+ MySQL 5.6+
* @package ExportMySQLUsers
* @author Zaid Daba'een
* @license http://www.dbad-license.org/ DBAD license
*
*
* Modified for AWS RDS
*/
// Set up database root credentials
$host = 'hostname';
$user = 'root';
$pass = 'your super secret password';
// ---- Do not edit below this ----
// Misc settings
header('Content-type: text/plain; Charset=UTF-8');
// Final import queries goes here
$export = [];
// Connect to database
try {
$link = new PDO("mysql:host=$host;dbname=mysql", $user, $pass);
}
catch (PDOException $e) {
printf('Connect failed: %s', $e->getMessage());
die();
}
// Get users from database
$statement = $link->prepare("select `user`, `host`, `authentication_string` FROM `user` WHERE `user` NOT IN ('root','rdsadmin','mysql.sys','mysql.session')");
$statement->execute();
while ($row = $statement->fetch()) {
$user = $row[0];
$host = $row[1];
$pass = $row[2];
$export[] = 'CREATE USER \'' . $user . '\'@\'' . $host . '\' IDENTIFIED BY \'' . $pass . '\'';
// Fetch any permissions found in database
$statement2 = $link->prepare('SHOW GRANTS FOR \'' . $user . '\'@\'' . $host . '\'');
$statement2->execute();
while ($row2 = $statement2->fetch()) {
$export[] = $row2[0];
}
}
$link = NULL;
echo implode(";\n", $export);
echo "\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment