dozpv84422 2014-07-16 12:37
浏览 47

如何用MySQLi编写的语句创建新的MySQL数据库用户?

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条回答 默认 最新

  • dongluan5740 2014-07-16 12:37
    关注

    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
    
    评论

报告相同问题?

悬赏问题

  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝