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

余生颓废 提交于 2019-12-11 12:40:31

问题


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

When I try to add new user without ? wildcards, everything is fine:

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

but even using CONCAT("'", ?, "'") for submitting data doesn't help.

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.


回答1:


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


来源:https://stackoverflow.com/questions/24780974/how-to-create-new-mysql-database-user-with-mysqli-prepared-statements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!