1

The database test_new_1 is able to create for the user testcom directly from the cpanel, But not able to create through php. Another server it is working properly, the only difference username and database prefix is same in that server.

Error Shows:

Error creating database: Access denied for user 'testcom'@'localhost' to database 'test_new_1' 

PHP

// Create connection
$conn = mysqli_connect('localhost', 'testcom', '123456');
// Check connection
if (!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}

// Create database
$sql = "CREATE DATABASE IF NOT EXISTS test_new_1";
if (mysqli_query($conn, $sql))
{
echo "Database created successfully";
}
else
{
echo "Error creating database: " . mysqli_error($conn);
}
3
  • 1
    In that case, it should not allow to create from cpanel also. But here can create from cpanel. Commented Jul 30, 2015 at 3:10
  • grant access to user testcom Commented Jul 30, 2015 at 3:21
  • 1
    Gave access, then all other projects databases shown in this user phpmyadmin, I have tried grant wildcard which not executed shows error. Commented Jul 30, 2015 at 4:21

1 Answer 1

4

cPanel does not allow you to create databases directly from with MySQL function. You need to use the API provided to you by cPanel:

Download xmlapi.php from https://github.com/CpanelInc/xmlapi-php/blob/master/xmlapi.php then use it:

<?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'));
?>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.