创建db和用户mysql并设置权限php

use*_*364 9 php mysql database privileges

有没有办法创建一个新的MySQL数据库,一个新的MySQL用户,并使用PHP为新数据库赋予新的用户权限?

Fab*_*geb 10

你可以这样做:

mysql_connect('localhost','user',password);
mysql_query("CREATE USER 'username'@'localhost' IDENTIFIED BY 'password';");
mysql_query("GRANT ALL ON db1.* TO 'username'@'localhost'");
mysql_query("CREATE DATABASE newdatabase");
mysql_close();
Run Code Online (Sandbox Code Playgroud)

您可以查看GRANTCREATE USER上的MySQL文档


You*_*nse 8

是的,因为所有这些操作都可以通过常规SQL查询来执行.

但是,我不会从root用户那里运行带有数据库连接的PHP脚本.

  • +1使用仅能够创建数据库和用户的专用帐户,因为它可以防止事故并在帐户遭到入侵时提供损坏限制.它不能丢弃任何东西,也无法访问数据. (7认同)

Tam*_*Pap 6

如果您在CPanel上托管项目,则该mysql_query方法将无法创建数据库,用户和授予权限.

您必须使用XML Api for CPanel.

<?php
include("xmlapi.php");

$db_host = 'yourdomain.com'; 
$cpaneluser = 'your cpanel username';
$cpanelpass = 'your cpanel password'; 

$databasename = 'testdb';
$databaseuser = 'test'; // Warning: in most of cases this can't be longer than 8 characters
$databasepass = 'dbpass'; // Warning: be sure the password is strong enough, else the CPanel will reject it

$xmlapi = new xmlapi($db_host);    
$xmlapi->password_auth("".$cpaneluser."","".$cpanelpass."");    
$xmlapi->set_port(2082);
$xmlapi->set_debug(1);//output actions in the error log 1 for true and 0 false  
$xmlapi->set_output('array');//set this for browser output  
//create database    
$createdb = $xmlapi->api1_query($cpaneluser, "Mysql", "adddb", array($databasename));   
//create user 
$usr = $xmlapi->api1_query($cpaneluser, "Mysql", "adduser", array($databaseuser, $databasepass));   
 //add user 
$addusr = $xmlapi->api1_query($cpaneluser, "Mysql", "adduserdb", array("".$cpaneluser."_".$databasename."", "".$cpaneluser."_".$databaseuser."", 'all'));
?>
Run Code Online (Sandbox Code Playgroud)

这里下载xmlapi.php ,或者只是在google上搜索它.

这对我来说非常有用.