Skip to content

Instantly share code, notes, and snippets.

@zaiddabaeen
Created February 23, 2016 11:47
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save zaiddabaeen/e88a2d10528e31cd6692 to your computer and use it in GitHub Desktop.
Save zaiddabaeen/e88a2d10528e31cd6692 to your computer and use it in GitHub Desktop.
Exports MySQL Users and Privileges using PDO
* Feel free to improve it.
* Original by Janich: https://gist.github.com/janich/6121771
*
* @requires PHP 5.3+
* @package ExportMySQLUsers
* @author Zaid Daba'een
* @license http://www.dbad-license.org/ DBAD license
*/
// Set up database root credentials
$host = 'localhost';
$user = 'root';
$pass = 'YOUR PASSWORD';
// ---- Do not edit below this ----
// Misc settings
header('Content-type: text/plain; Charset=UTF-8');
// Final import queries goes here
$export = array();
// 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`, `password` FROM `user`");
$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();
if ($row2 = $statement2->fetch())
{
$export[] = $row2[0];
}
}
$link = null;
echo implode(";\n", $export);
@ale10257
Copy link

ale10257 commented May 9, 2017

Error on line 38
if ($row2 = $statement2->fetch())
Must be
while ($row2 = $statement2->fetch())

If mysql version > 5.6
On line 27 must be
$statement = $link->prepare("select user, host, authentication_stringFROMuser");
(not field password in table User)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment