¿Existe alguna manera de crear una nueva base de datos MySQL, un nuevo usuario de MySQL y otorgar privilegios a los nuevos usuarios en la nueva base de datos usando PHP?create db and user mysql and set privileges php
Respuesta
Sí, ya que todas estas acciones se pueden realizar mediante consultas regulares de SQL.
Sin embargo, me abstendría de ejecutar scripts PHP con conexión de base de datos desde el usuario raíz.
Se podría hacer algo como esto:
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();
Usted puede mirar la documentación de MySQL en GRANT y CREATE USER
Si usted es anfitrión de su proyecto en CPanel, entonces el método mysql_query
no funcionará a crear bases de datos, usuarios y otorgar permisos.
Debe utilizar XML Api para 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'));
?>
Descargar xmlapi.php de here, o simplemente buscar en Google para ello.
Esto es lo que funcionó para mí a la perfección.
Base de datos creada Tanto el usuario como el usuario también se crearon correctamente pero el usuario recién creado no se asignó a la base de datos. –
puede descargar el xmlapi.php desde aquí: https://github.com/CpanelInc/xmlapi-php/blob/master/xmlapi.php (se mueve el enlace de descarga en la respuesta) – sudip
<!--
Go to setup on line 48
Created by [email protected]
-->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="en-gb" http-equiv="Content-Language" />
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Create Database</title>
</head>
<body>
<!-- Title -->
<p><h1>Create Database</h1></p>
<p></p>
<p>
<!-- The form -->
<form action="<?php $currentFile = $_SERVER["PHP_SELF"];$parts = Explode('/', $currentFile);echo $parts[count($parts) - 1];?>" method="post">
Database Name: <input name="databasename" type="text" />
<br>
DB Pass: <input name="dbpass" type="text" />
<br>
Admin Pass: <input name="passbox" type="password" />
<p><input name="Submit1" type="submit" value="submit" /></p>
</form>
<!-- end form -->
</p>
</body>
</html>
<?php
//*********************** CONFIG SETUP ************************************//
// Created by [email protected]
//
// set the admin pass for the page
$adminpass = "*******"; // change ******* with your page pass
//
// set mysql root pass
$mysqlRootPass = "*******"; // change ******* with your mysql root pass
//
//
//*********************** CONFIG SETUP ************************************//
// if isset set the varibables
if(isset($_POST["passbox"]) && ($_POST["databasename"])){
$databasename = $_POST["databasename"];
$password = $_POST["passbox"];
$dbpass = $_POST["dbpass"];
}
else { exit;}
if(($password) == ($adminpass)) {
}
else {
echo "Incorrect Password!";
exit;}
// store connection info...
$connection=mysqli_connect("localhost","root","$mysqlRootPass");
// check connection...
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Create database
echo "<br><br>";
#echo "$sql";
$sql="CREATE DATABASE $databasename";
if (mysqli_query($connection,$sql))
{
echo "<h2>Database <b>$databasename</b> created successfully!</h2>";
}
else
{
echo "Error creating database: " . mysqli_error($con);
}
// Create user
$sql='grant usage on *.* to ' . $databasename . '@localhost identified by ' . "'" . "$dbpass" . "'";
echo "<br><br>";
#echo "$sql";
if (mysqli_query($connection,$sql))
{
echo "<h2>User Created... <b>$databasename</b> created successfully!</h2>";
}
else
{
echo "Error creating database user: " . mysqli_error($con);
}
// Create user permissions
$sql="grant all privileges on $databasename.* to [email protected]";
echo "<br><br>";
#echo "$sql";
if (mysqli_query($connection,$sql))
{
echo "<h2>User permissions Created... <b>$databasename</b> created successfully!</h2>";
}
else
{
echo "Error creating database user: " . mysqli_error($con);
}
echo "<p>Database Name: $databasename</p>";
echo "<p>Database Username: $databasename</p>";
echo "<p>Database Password: $dbpass</p>";
echo "<p>Database Host: localhost</p>";
?>
Esto no intenta responder al pregunta. –
le sugiero que utilice phpmyadmin.
que tiene que hacer pasos:
- phpmyadmin abierta
- ir a la sección de administración
- hit en cuenta de usuario complemento
- nombre de usuario put y contraseña
- privilegios que se
- hit el botón [ir]
eso es todo ver en acción en YouTube [click here]
en el caso si usted quiere saber más sobre phpMyadmin go with official
pero si hay alguna razón especial para hacerlo con php el aquí es el commend sql
CREATE USER 'tesrytss'@'%'//user name IDENTIFIED VIA mysql_native_password USING '***';.//set pass GRANT SELECT, INSERT, UPDATE, DELETE, FILE ON *.* TO 'tesrytss'@'%' // previlages and username and location REQUIRE NONE WITH MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0; //other requerment
- 1. mysql CREATE USER
- 2. Web User Controls and Validation
- 3. ASP.NET Authorize attribute and Admin user role
- 4. PHP MySQL Search And Order By Relevancy
- 5. semáforo de Javascript/test-and-set/lock?
- 6. using fancybox set height and width
- 7. JQGrid set caption and column name
- 8. ¿Para qué se usa Test-and-Set?
- 9. (OrElse and Or) and (AndAlso and And) - ¿Cuándo usar?
- 10. greendao delete from db and session
- 11. Devise and Rails - ArgumentError in Devise :: RegistrationsController # create
- 12. PHP Lexer and Parser Generator?
- 13. Authenticate user from iOS Rails 3 server and Omniauth
- 14. Seleccione Parent and Children With MySQL
- 15. struct and class and inheritance (C++)
- 16. oracle and i18n support
- 17. nulo con PHP < and > operadores
- 18. Zend-marco DB: O en lugar de operador AND
- 19. nhibernate Restrictions.Eq and null
- 20. Time and Nhibernate
- 21. declarative_authorization and namespaces
- 22. Lua getters and setters
- 23. $ function() and $$ variable
- 24. SQLiteDatabases and Cursors
- 25. XML Diff and Merge
- 26. TransactionScope and Transactions
- 27. Node.js and Redis Auth
- 28. Create User in Devise de JSON
- 29. Fluido NHibernate genera AND AND Assigned ID Columns
- 30. Python Requests and Unicode
+1 utilizar una cuenta dedicada que sólo es capaz de crear bases de datos y los usuarios, ya que evita accidentes y proporciona la limitación del daño si se compromete la cuenta. No puede soltar nada y no tiene acceso a los datos. –
plus1 Muy buen punto ... –