Can't create database from coding but can from cpanel - php

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);
}

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'));
?>

Related

Which username/password do I use to connect to mySQL

So, I'm SUPER new to mySQL. Having issues connecting to my database with PHP. Hoping someone can point me in the right direction.
I can login to our Cpanel using my username/password. Using the web gui I was able to create a database.
Now when I try to connect to the database (or even just the server for that matter) using PHP I get an error:
Warning: mysqli::__construct(): (HY000/1045): Access denied for user 'username'#'servername' (using password: YES) in /home/ropepart/public_html/techportal/sandbox/mysqltest.php on line 8
Connection failed: Access denied for user 'username'#'servername' (using password: YES)
To me, it seems like this is a username/password error. But I an using the same username/password that I use to login to the web gui. Why can I successfully login there, but can't login with PHP?
Here's my code (taken pretty much directly from W3Schools):
<?php
$servername = "servername";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
(Hopefully it's obvious that I've changed my servername/username/password for the purposes of this post)
Check the details correctly, By deafult
host = localhost
username = root
password = (No password leave it as empty)
database = (your database)
<?php
$connection = new mysqli('host','username','password','your_database');
if($connection->connect_error || $connection->error){
echo "error";
}else{
echo "done";
}
?>
you should add database name.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "demo"
// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
//if you are using xampp you shoul locate this file you get information from this
passwords.txt
MySQL database username/password is not necessarily same as cPanel username & password.
Here is what you should do:
Login to your cPanel
From dashboard click "MySQL® Databases"
Add a new user from there (https://prnt.sc/kpiby9). Just fill username
and password (note down the password).
Add that user with your database by selecting both from the dropdown
(https://prnt.sc/kpidqx)
Now, use this username & password to connect with the database.
mysqli_connect(serverhostname,username,password,dbname);

Is it possible to obtain a cpanel mysql database prefix?

$db_connection = $_SERVER['DOCUMENT_ROOT'] . '/includes/install/database_connection.php';
if (!file_exists($db_connection)) {
require("install/xmlapi.php");
if (isset($_POST['cpname'])) {
$opts['user'] = $_POST['cpname'];
$opts['pass'] = $_POST['cppass'];
$opts['temp'] = substr(str_shuffle(md5(time())),0,'12');
$xmlapi = new xmlapi($_SERVER['HTTP_HOST']);
$xmlapi->set_port( 2083 );
$xmlapi->password_auth($opts['user'],$opts['pass']);
$xmlapi->set_debug(0);
$cpaneluser=$opts['user'];
$databasename="OSMP_DAT";
$databaseuser="OSMP_admin";
$databasepass=$opts['temp'];
$db = $databasename;
$user = $databaseuser;
$pass = $databasepass;
$loc = 'localhost';
$createdb = $xmlapi->api1_query($cpaneluser, "Mysql", "adddb", array($databasename));
$usr = $xmlapi->api1_query($cpaneluser, "Mysql", "adduser", array($databaseuser, $databasepass));
$addusr = $xmlapi->api1_query($cpaneluser, "Mysql", "adduserdb", array("".$cpaneluser."_".$databasename."", "".$cpaneluser."_".$databaseuser."", 'all'));
include ('install/installer.php');
exit;
}
if (!isset($_POST['dbhost'])) { include ('install/db_installer.php'); }
if (isset($_POST['dbhost'])) {
// save connection details to $db_connection
}
}
The above code works flawlessly as one would expect.
First it checks for the existence of database_connection.php. If it exists, it includes the file which contains database details.
If not - we are assuming its a first time install. So we are asking a user for cpanel login details, and our script creates the database and saves details to database_connection.php.
The only problem ... is database prefixes. When the database is created, if the WHM has database prefixes set for the user account, then a database prefix is prefixed to the database name.
I want to know how to determine if there is a prefix, and if so how to find out what it is so the script can prefix it on the database name as well.
Note I am not seeking a table prefix, but rather the database prefix as added by cpanel/whm
So apparently cpanel by default if prefixing is enabled used the first 8 characters of ones username followed by an underscore. This is used for both database and database names.
So I simply modified the above code as follows:
$db_connection = $_SERVER['DOCUMENT_ROOT'] . '/includes/install/database_connection.php';
if (!file_exists($db_connection)) {
require("install/xmlapi.php");
if (isset($_POST['cpname'])) {
$opts['user'] = $_POST['cpname'];
$prefix = substr($opts['user'],0,8).'_';
if ($prefix === FALSE) {$prefix = $opts['user'];}
$opts['pass'] = $_POST['cppass'];
$opts['temp'] = substr(str_shuffle(md5(time())),0,'12');
$xmlapi = new xmlapi(localhost);
$xmlapi->set_port( 2083 );
$xmlapi->password_auth($opts['user'],$opts['pass']);
$xmlapi->set_debug(1);
$cpaneluser=$opts['user'];
$databasename="OSMP_DAT";
$databaseuser="osmp";
$databasepass=$opts['temp'];
$pass = $databasepass;
$loc = 'localhost';
$createdb = $xmlapi->api1_query($cpaneluser, "Mysql", "adddb", array($databasename));
$usr = $xmlapi->api1_query($cpaneluser, "Mysql", "adduser", array($databaseuser, $databasepass));
$addusr = $xmlapi->api1_query($cpaneluser, "Mysql", "adduserdb", array($databasename, $databaseuser, 'all'));
$db = $prefix.$databasename;
$user = $prefix.$databaseuser;
include ('install/installer.php');
exit;
}
if (!isset($_POST['dbhost'])) { include ('install/db_installer.php'); }
if (isset($_POST['dbhost'])) {
// save connection details to $db_connection
}
}
So now a check is done to determine the length of the username and if longer than 8 characters, its truncated to 8. Then the understore is added and output as variables to pass along to the next part of the script.
The only flaw left as I can see is if the host has disabled the prefixing in whm, so I am well on my way.
For anyone attempting to use this code in the future - make note you
need to secure the included files or you are going to have whopping
security problems. As this code stands someone could manually call
install/db_installer.php or install/installer.php and bypass the
(!file_exists($db_connection)) check and the if (isset($_POST)) and
the (!isset($_POST['dbhost'])).
DO NOT USE THIS CODE IF YOU DON'T KNOW HOW TO SECURE IT!

PHP: Is it possible to execute a MySQL statement to create a DATABASE even though I am already connected to my database?

I've been wondering if it's possible to create a new database using mysqli_query() even though I'm already connected to my database?
$create_new_db = mysqli_query($user_conn, "CREATE DATABASE sample_db");
if($create_new_db) {
echo 'new database has been created';
} else {
echo 'Error while creating new database.';
}
my variable $user_conn has a database connection named db_maindb. So is it still possible to create a new database when I'm connected to my db_maindb database?
Like you have in you code ..
assuming you can connect to an existing database and your connected user has grant for create database you can
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Create database
$sql = "CREATE DATABASE sample_db";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}
$conn->close();
?>

Create mysql DB with PHP through cPanel and import *.sql file

I want to create a DB for each user who wants to register to my Web-app. When i try this local everything perfectly works. A User can register with his email and pw. A DB is created and a import.sql file is imported so that the DB created for the User is empty on data but the tables and realtioships are given.
My Host uses cPanel and phpMyAdmin to create DB and db-user. I want to do this with php like i do it local. Does anyone have an idea how i get this done?
I've already searched and tryed stuff out but nothing works for me.
If possible some explanations on cPanel maybe would be enough.
<?php
require("xmlapi.php"); // this can be downlaoded from https://github.com/CpanelInc/xmlapi-php/blob/master/xmlapi.php
$xmlapi = new xmlapi("cpanlel host name");
$xmlapi->set_port( 2083 );
$xmlapi->password_auth('cpanel username','cpanel passsword');
$xmlapi->set_debug(0);//output actions in the error log 1 for true and 0 false
$cpaneluser='cpanel username';
$databasename="something";
$databaseuser="database username";
$databasepass= 'database password';
//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('' . $databasename . '', '' . $databaseuser . '', 'all'));
?>
Using the above code you will be able to create new database, add new user to database and give all access to user on database.

Create Databases Dynamically with Google Cloud SQL and PHP

I am trying to have a database created for each user that signs up for my web app. This database will be based on a template to store their data.
The problem I'm running into is that Google Could SQL doesn't seem to be creating the Database via PHP and MySQL queries.
Connecting to the Instance works fine and triggers no errors based on this code:
//CLOUD SQL CONNECTION FOR SUBSCRIPTIONS
$hostname = details;
$username = details;
$password = details;
$port = details;
$socket = details;
$connection = new mysqli($hostname, $username, $password, $port, $socket);
// Check Connection
if($connection->connect_error) {
trigger_error('Connection failed: ' . $connection->connect_error, E_USER_ERROR);
}
However, when I go to create a simple database, mysqli fails without an error...:
//Create Database
$username = 'account';
$database = 'sub_'. $username .'_db';
$query = "CREATE DATABASE IF NOT EXISTS `{$database}`;";
if(mysqli_query($connection, $query)) {
echo "Database my_db created successfully";
} else {
echo "Error creating database: " . mysqli_error($connection);
}
The output of this is simply: Error creating database:
Am I missing something? How do I create a database in a Cloud SQL instance via PHP? Thanks for any input.
Can anyone confirm that this can actually be done on GAE PHP and Cloud SQL?
It seems the $connection variable was actually NULL despite not throwing an error. This worked for me though:
I connected to an existing database:
//CLOUD SQL CONNECTION FOR SUBSCRIPTIONS
$hostname = details;
$username = details;
$password = details;
$db = details;
$port = details;
$socket = details;
$connection = new mysqli($hostname, $username, $password, $db, $port, $socket);
// Check Connection
if($connection->connect_error) {
trigger_error('Connection failed: ' . $connection->connect_error, E_USER_ERROR);
}
Then I created a new database:
//Create Database
$username = 'account';
$database = 'sub_'. $username .'_db';
$query = "CREATE DATABASE IF NOT EXISTS `{$database}`;";
if(mysqli_query($connection, $query)) {
echo "Database my_db created successfully";
} else {
echo "Error creating database: " . mysqli_error($connection);
}
Then used mysqli_select_db() to select the newly created database.
//Select Newly Created DB
mysqli_select_db($connection, $database);

Categories