How to Export & Import Existing User (with its Privileges!)

后端 未结 9 1999
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-03 17:01

I have an existing MySQL instance (test), containing 2 databases and a few users each having different access privileges to each database.

I now need to duplicate one of

9条回答
  •  遇见更好的自我
    2021-02-03 17:48

    A PHP script to loop over your users to get the grant commands would be as such:

    // 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);
    

    Gist: https://gist.github.com/zaiddabaeen/e88a2d10528e31cd6692

提交回复
热议问题