数据库 test_new_1 能够直接从cpanel为用户 testcom 创建,但无法通过php创建。另一台服务器正常工作,唯一不同的用户名和数据库前缀在该服务器中是相同的。
错误显示:
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);
}
答案 0 :(得分:3)
cPanel不允许您直接使用MySQL函数创建数据库。您需要使用cPanel提供给您的API:
从https://github.com/CpanelInc/xmlapi-php/blob/master/xmlapi.php下载xmlapi.php
,然后使用它:
<?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'));
?>