简体   繁体   English

如何使用MySQLi准备的语句创建新的MySQL数据库用户?

[英]How to create new MySQL database user with MySQLi prepared statements?

I'm trying to add new database user by these statements: 我正在尝试通过以下语句添加新的数据库用户:

$insert = $db->prepare("CREATE USER ? IDENTIFIED BY ?");
$insert->bind_param('ss', $_POST['username'], $_POST['pass']);
$insert->execute();

Database gives me error: You have an error in your SQL syntax; (...) near '? IDENTIFIED BY ?' at line 1 数据库给我错误: You have an error in your SQL syntax; (...) near '? IDENTIFIED BY ?' at line 1 You have an error in your SQL syntax; (...) near '? IDENTIFIED BY ?' at line 1

When I try to add new user without ? 当我尝试添加新用户时没有? wildcards, everything is fine: 通配符,一切都很好:

CREATE USER john IDENTIFIED BY 'johnpassword' //this works , CREATE USER john IDENTIFIED BY 'johnpassword' //this works

but even using CONCAT("'", ?, "'") for submitting data doesn't help. 但是即使使用CONCAT("'", ?, "'")提交数据也无济于事。

I read in MySQL documentation that MySQL 5.7 should support prepared statements for CREATE USER SQL statement, but with MySQLi it doesn't seem to. 我在MySQL文档中读到,MySQL 5.7应该支持CREATE USER SQL语句的预准备语句,但是对于MySQLi,似乎不支持。

I have omitted this problem by setting values in database's variables : 我通过在数据库变量中设置值来省略了此问题:

    $insert = $db->prepare("SET @username = ? "); //store username in variable in database
    $insert->bind_param('s', $_POST['username']);
    $insert->execute();
    $insert = $db->prepare("SET @password = ? "); //store password in variable in database
    $insert->bind_param('s', $_POST['pass']);
    $insert->execute();

    $insert = $db->query("SET @query1 = CONCAT('CREATE USER ', @username,' IDENTIFIED BY \'', @password, '\'')");
    if ($insert == false) {
        print ($db->error);
    }
    $insert = $db->multi_query("PREPARE stmt FROM @query1"); //create user by using initialized variables. Note that you dont need to use prepared statements now
        if ($insert == false) {
        print ($db->error);
    }
    $insert = $db->query("EXECUTE stmt;");
    if ($insert == false) {
        print ($db->error);
    }
    $insert = $db->query("DEALLOCATE PREPARE stmt;");
    if ($insert == false) {
        print ($db->error);
    }
    $insert = $db->query("SET @password = null"); //clear plaintext password for safety reasons

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM