Created
February 23, 2016 11:47
-
-
Save zaiddabaeen/e88a2d10528e31cd6692 to your computer and use it in GitHub Desktop.
Exports MySQL Users and Privileges using PDO
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
* 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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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_stringFROM
user");
(not field password in table User)