/    Sign up×
Community /Pin to ProfileBookmark

Use PHP to Create Database

I am trying to use PHP to create a mySQL database. I can create it using cPanel. I enter the name of the database in the input box and cPanel automatically prepends my account name. So if I enter “my_db”, cPanel creates a database with the name of account_name_my_db.

Here is my code:

[code=php]
<?php

$dbServer = “mysql”;
$dbHostname = “localhost”;
$dbUsername = “account_name”;
$dbPassword = “abc1234”;
$dbName = “account_name_a10000”;

$link = mysql_connect($dbHostname, $dbUsername, $dbPassword);
if (!$link) {
die(‘Could not connect: ‘ . mysql_error());
} else {

echo “<br>connected<br><br>”;
}

$sql = ‘CREATE DATABASE account_name_my_db’;
if (mysql_query($sql, $link)) {
echo “Database account_name_my_db created successfullyn”;
} else {
echo ‘Error creating database: ‘ . mysql_error() . “n”;
}

$sql = ‘CREATE DATABASE my_db’;
if (mysql_query($sql, $link)) {
echo “<br><br>Database my_db created successfullyn”;
} else {
echo ‘<br><br>Error creating database: ‘ . mysql_error() . “n”;
}

?>
[/code]

His what I ge when I run this code:

[code=html]
connected

Error creating database: Access denied for user ‘account_name’@’localhost’ to database ‘account_name_my_db’

Error creating database: Access denied for user ‘account_name’@’localhost’ to database ‘my_db’
[/code]

Why doesn’t this code work…?

.

to post a comment
PHP

1 Comments(s)

Copy linkTweet thisAlerts:
@NogDogOct 15.2008 — Probably the database user being used by your script does not have the necessary permissions to do a create database operation.

Many hosting companies do not even provide the option to assign that permission to your database user accounts, requiring you to use their control panel application to create/drop databases. Presumably this is done to protect careless/ignorant users from either accidentally destroying their database or leaving security holes that allow hackers to do so.
×

Success!

Help @esm spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.4,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...