如何使用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();
数据库给我错误:
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
,
,但是即使使用CONCAT("'", ?, "'")
提交数据也无济于事.
but even using CONCAT("'", ?, "'")
for submitting data doesn't help.
我在MySQL文档中读到,MySQL 5.7应该支持CREATE USER
SQL语句的预准备语句,但是对于MySQLi来说似乎并不.
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.
推荐答案
我已经通过在数据库变量中设置值而忽略了这个问题:
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
这篇关于如何使用MySQLi准备的语句创建新的MySQL数据库用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!