mysqli access denied (42000/1044) linux permissions? - php

I get the php error
mysqli::mysqli(): (42000/1044): Access denied for user
'sec_user01'#'localhost' to database 'secure_login'
I created the database with:
CREATE DATABASE `secure_login`;
I created the user with
CREATE USER 'sec_user'#'localhost' IDENTIFIED BY '**********************';
GRANT SELECT, INSERT, UPDATE ON `secure_login`.* TO 'sec_user'#'localhost';
I connect to the db using
include_once 'web_psl-config.php'; // As functions.php is not included
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
the config file is included successfully.
this worked up till a few hours ago.
The only thing I can think of that changed is that in my php script I made some folders with 755 access. Is it possible that the permissions from the files from which this script is executed are causing this error ?
I am really stumped.
edit: I tested this with an ADODB connection
require('../scripts/adodb5/adodb.inc.php');
$ADODB_CACHE_DIR = 'adodb5cache';
$Host = "localhost";
$Database = "secure_login";
$Databasetype ="mysql";
// lijst users en passwd
$DbAdminUser="sec_user01";
$DbAdminUserPassword="**************";
$debug = true; //debug on
//$debug = false; //debug off
//admin connection
$dbconn = ADONewConnection($Databasetype);
$dbconn->Connect($Host, $DbAdminUser, $DbAdminUserPassword, $Database);
$query="SELECT * FROM members;";
$ammount=$dbconn->GetAll($query);
print_r($ammount);
and this works. Is this some kind of bug in mysqli ?
I really hope I don't have to rewrite to use ADODB.

Login to your cpanel (www.example.com/cpanel)
Go to MySQL add database wizard
similar to "add database", "add_user" you will have a button
to add user" to the "database".
click on it,
added user should list under "priviledged user" for that "database".

Try to login into phpmyadmin with those credentials. If unsuccessful then your credentials might not matching.

The grant statement was wrongly formatted
GRANT SELECT, INSERT, UPDATE ON `secure_login`.* TO 'sec_user'#'localhost'; is wrong
GRANT SELECT, INSERT, UPDATE ON secure_login.* TO 'sec_user'#'localhost'; works.
Why did it work the first time I have no idea.

i have had this error a few times before, and to my understanding, which is limited on this error is that a many of things could be causing it, first and foremost try to reset your password, the way you do this is by going into a terminal and type.
$ mysqladmin -u root -p'oldpassword' password newpass
make notice to fill in your credentials where oldpassword, password, and newpass.
then try my php script i made, it will show you what fields you left blank and will use default parameters for them if they are still blank. the comments that pop up will also disappear within 10 seconds.
file 1
index.php
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" /><meta http-equiv="content-language" content="en-US" />
<title>MySQL Connection test</title>
<script type="text/javascript">
window.onload = function()
{
timedHide(document.getElementById('messages'), 10);
}
function timedHide(element, seconds)
{
if (element) {
setTimeout(function() {
element.style.display = 'none';
}, seconds*1000);
}
}
</script>
</head>
<body>
<span id="messages">
<?php include "constant.php"; ?>
</span>
</body>
</html>
file 2
constant.php
<?php
$database_ip = ""; //database ip adress goes inside quotes
$database_port = ""; //database port goes inside quotes
$database_name = ""; //database name goes inside quotes
$database_admin_user = ""; //admin username goes inside quotes
$database_admin_pass = ""; //admin password goes inside quotes
//do not modify anything past this point unless you know php well.
$database_link = null;
$database_defaults = array("127.0.0.","3306","MySQL","root","");
$error_defaults = array("error_no_101" => "required field *IP is empty, using default parameters!",
"error_no_102" => "required field *PORT is empty, using default parameters!",
"error_no_103" => "required field *NAME is empty, using default parameters!",
"error_no_104" => "required field *USER is empty, using default parameters!",
"error_no_105" => "required field *PASS is empty, using default parameters!");
if(empty($database_ip)){
$database_ip = $database_defaults[0];
echo $error_defaults["error_no_101"] . "<br/>";
}
if(empty($database_port)){
$database_port = $database_defaults[1];
echo $error_defaults["error_no_102"] . "<br/>";
}
if(empty($database_name)){
$database_name = $database_defaults[2];
echo $error_defaults["error_no_103"] . "<br/>";
}
if(empty($database_admin_user)){
$database_admin_user = $database_defaults[3];
echo $error_defaults["error_no_104"] . "<br/>";
}
if(empty($database_admin_pass)){
$database_admin_pass = $database_defaults[4];
echo $error_defaults["error_no_105"] . "<br/>";
}
$database_link = mysqli_connect($database_ip, $database_admin_user, $database_admin_pass, $database_admin_pass);
if (!$database_link) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
echo 'Success... ' . mysqli_get_host_info($database_link) . "\n";
mysqli_close($database_link);
?>
i hoped this helped (=

THis error disappear when you add some privileges except the insert select update in user privileges!
So go add add all the privileges in cpanel with username and database name.

Related

User not being deleted on link click [duplicate]

This question already has answers here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Reference - What does this error mean in PHP?
(38 answers)
Closed 5 years ago.
I have a users table and I want to be able to delete a user when a link is clicked. $user_name is set in a session. Here is the link:
<?php echo "Delete Account" ?>
Here is the code on delete_user.php:
<?php
session_start();
session_destroy();
require "connection.php";
?>
<?php
if($_GET['id'] != ""){
$user_name = $_GET['id'];
$sql = "DELETE FROM users WHERE user_name='{$user_name}'";
$result = mysqli_query($connection, $sql);
header('Location: register.php');
}
?>
<?php include "footer.php";?>
I don't understand why it's not deleting the user from the database when this code is executed?
There's no clear reason as to why your code is not working. However, you mentioned being new to PHP, so picking up good practices with your code could (1) help solve the issue at hand, (2) make your code more efficient, and easier to debug.
I recommend you use mysqli in the object-oriented manner, it requires less code, and usually easier to follow.
Making the connection is simple:
<?php
$host = 'localhost';
$user = 'USERNAME';
$pass = 'PASS';
$data = 'DATABASE';
$mysqli = new mysqli($host, $user, $pass, $data);
// catch errors for help in troubleshooting
if ($mysqli->errno)
{
echo 'Error: ' . $mysqli->connect_error;
exit;
}
?>
Creating a safe environment for your server keep in mind these things:
Do not trust user input (ever!)
Do not perform direct queries into your database.
When developing, break your code into steps so you can easily troubleshoot each part.
With those three simple things in mind, create a delete file.
<?php
if (isset($_GET['id'])
{
// never trust any user input
$id = urlencode($_GET['id']);
$table = 'users';
// set a LIMIT of 1 record for the query
$sql = "DELETE FROM " . $table . " WHERE user_name = ? LIMIT 1";
// to run your code create a prepared statement
if ($stmt = $mysqli->prepare( $sql ))
{
// create the bind param
$stmt->bind_param('s', $id);
$stmt->execute();
$message = array(
'is_error' => 'success',
'message' => 'Success: ' . $stmt->affected_rows . ' were updated.'
);
$stmt->close();
}
else
{
$message = array(
'is_error' => 'danger',
'message' => 'Error: There was a problem with your query'
);
}
}
else
{
echo 'No user id is set...';
}
The code will help you set the query, and delete the user based on their user_name... Which I am not sure that is the best solution, unless user_name is set to be an unique field on your MySQL database.
Firstly this is a horrible way to do this, you are prone to SQL Injections and also using GET literally just tags the query to the end of the URL which is easily obtainable by a potential hacker or ANY user as a matter of fact. Use POST instead with a bit of jQuery magic, I would also recommend using Ajax so that you don't get redirected to php file and it will just run. As it is not anyone can access that URL and delete users so I recommend using PHP SESSIONS so that only people from your site can delete users. Also simply passing the id to the PHP file is very insecure as ANYONE could simply create a link to your php file on their site and delete users.
Therefore try this to fix your code (with added security):
PLEASE NOTE: I am aware that this may not be the best way nor the worst but it is a fairly secure method that works well.
Your main page, index.php:
<?php
session_start();
// Create a new random CSRF token.
if (! isset($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = base64_encode(openssl_random_pseudo_bytes(32));
}
// Check a POST is valid.
if (isset($_POST['csrf_token']) && $_POST['csrf_token'] === $_SESSION['csrf_token']) {
// POST data is valid.
}
?>
...
<form id="delete_user_form" action="delete_user.php" method="post">
<input type="hidden" name="user_id" value="<?php echo $user_name; ?>" />
<input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>" />
<input type="submit" value="Delete User" />
</form>
In your .js file (make sure you have jQuery linked):
window.csrf = { csrf_token: $("input[name= csrf_token]").val() };
$.ajaxSetup({
data: window.csrf
});
$("#delete_user_form").submit(function(event) {
event.preventDefault(); //Stops the form from submitting
// CSRF token is now automatically merged in AJAX request data.
$.post('delete_user.php', { user_id: $("input[name=user_id]").val() }, function(data) {
//When it it's complete this is run
console.log(data); //With this you can create a success or error message element
});
});
Now for your delete_user.php file, this should fix the errors:
<?php
session_start();
require "connection.php";
// Checks if csrf_token is valid
if (isset($_POST['csrf_token']) && $_POST['csrf_token'] === $_SESSION['csrf_token']) {
if(isset($_POST['user_id']) && $_POST['user_id'] != ""){
$user_name = $_POST['user_id'];
$sql = "DELETE FROM users WHERE user_name = '$user_name' LIMIT 1"; //LIMIT 1 only allows 1 record to be deleted
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully"; //You get this in your javascript output data variable
} else {
echo "Error deleting record: " . $conn->error; //You get this in your javascript output data variable
}
$conn->close();
}
}
?>
I don't know what your connection.php contains so this is what I'd put in it:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

Call to member function on a non-object (include database.php)

I am working on a new website, and I rewrote some of my previously working code for the new one to recreate the login system. Unfortunately, the rewritten version does not work so let me explain what's going on.
I have "index.php", which holds the "titlemenu.php" that is used on every single page. I intend to run the login box in this title menu (top bar) so people can log in despite what page their own, and when they successfully log in, it refreshes the page they are currently on so they're logged in.
So far, bingo - It works. They're logged in and view members only pages. However, the title bar is a different story. It still shows "LOG IN" and "REGISTER", despite being logged in. Immediatelly, I though this was a problem with that specific php file, so I logged into that php only, bypassing index. When I try to sign in on that blank page only, I get:
Fatal Error: Call to a non-member function prepare() on line 18
I know this usually means your variable is not declared or not being ran, so I decided to troubleshoot it. I did a var_dump on every variable I used, which returned valid results. I checked index.php, which has no errors and runs fine, and shows users as logged in. "Welcome Back, RhapidFyre!" is what it says on the index, but the login box shows that I am not logged in yet.
loginheader.php
<?include "641a/database.php";?><div id="login"><?
$mydbid = $_SESSION['user'];
$myquery = "SELECT * FROM logins WHERE dbid = $mydbid";
$myrow = mysqli_fetch_assoc($myquery);
$myname = $myrow['nickname'];
if($_GET['do'] == "logout") {
unset($_SESSION['user']);
?><script type="text/javascript">
window.location.replace("index.php");
</script><?
}
if($_GET['do'] == 'login') {
$query = 'SELECT * FROM logins WHERE username = :username';
$query_params = array(':username' => $_POST['username']);
var_dump($query);
var_dump($query_params);
try
{
$stmt = $db->prepare($query); //LINE 18
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
?><script type="text/javascript">
window.location.replace("redirect.php?error=username");
</script><?
}(Further irrelevant code follows)
database.php
<? session_start();
$dbusername = "********";
$dbpassword = "********";
$dbhost = "localhost";
$dbname = "********";
$link = mysqli_connect($dbhost, $dbusername, $dbpassword, $dbname);
// PDO Initialization
try {
$db = new PDO("mysql:host={$dbhost};dbname={$dbname};charset=utf8", $dbusername, $dbpassword);
}
// If connection fails, die.
catch(PDOException $ex){
die("Failed to connect to the MySQL Server!" . $ex->getMessage());
}
Snippet of index.php
<html>
<head>
<title>My Website Template</title>
<link rel="stylesheet" type="text/css" href="base.css"/>
</head>
<body>
<div id="header">
<?include "pages/titles.php";?>
<?include "pages/loginheader.php";?>
</div>
The problem stemmed from using two connection types while trying to debug. Changed it all to MySQLi and it ran fine, but created new problems. As my programming instructor used to say, "Yay! New errors!"

Page source reveals part of my page isn't displaying

I'm working on a friend's project and I'm in charge of designing a simple website to interface with his databases. I have written the following code for one of his pages:
<!DOCTYPE html>
<html>
<head>
<title>Narcissus-OTS</title>
<meta charset="utf-8" />
<!--<meta http-equiv="refresh" content="3;url=./account.php" />-->
</head>
<body>
<?php include("./common/database.php"); ?>
<?php
//Grabs user-submitted credentials from previous page
$accountid = mysql_escape_string($_POST["acc"]);
$password = mysql_escape_string($_POST["pass"]);
$confirmation = mysql_escape_string($_POST["passtwo"]);
//Insures there is no duplicate database entry for accountid
$querycheck = $db->query("
SELECT *
FROM accounts a
WHERE a.name = $accountid
");
$checkifone = $querycheck->rowCount();
//If no duplicate entry...
if ($checkifone == 1) {
echo "There is already an account with that name; please choose a different account number.";
} else {
//Confirms if passwords match
if ($password == $confirmation) {
$passhash = sha1($password);
$database = $db->query("
INSERT INTO accounts
VALUES (NULL , '$accountid', '$passhash', '65535', '0', '', '1', '0', '0', '1');
");
echo "Your account has been successfully created.";
//If passwords do not match
} else {
echo "Your passwords did not match, please try again.";
}
}
?>
</body>
</html>
When I load the page and view page source, it doesn't seem to show terminating </body> or terminating </html> tags. I've traced my code and can't see any missing semi-colons or parentheses. For the life of me I can't figure this one out. It displays the terminating tags properly only when the passwords do not match (the bottom-most nested else statement).
edit; and before anyone says it, I know mysql_escape_string is deprecated.
edit2; database.php looks like...
<?php
$SERVER = "localhost";
$USERNAME = "redacted";
$PASSWORD = "redacted";
$DATABASE = "redacted";
$db = new PDO("mysql:dbname={$DATABASE}; host={$SERVER}", $USERNAME, $PASSWORD);
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
?>
Your best bet to solve this problem and any other occurrences like this in the future is to tail your server log and determine what exactly the issue is.
For apache2:
tail -f /var/log/apache2/error.log
For nginx:
tail -f /var/log/nginx/error.log

PHP Include another php that queries MySQL

In my site im trying to include on the top of each page a "banner" that is itself a separate php page that queries a MySQL database to return a number that displays.
When i goto the exact URL of the banner php url (www.sitename.com/banner.php) it works perfectly.
However, when i include the banner into another page include'banner.php' it returns the following error: Database access error 2002: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)
I have 2 ways i need to include this, my main site pages are all php. My forum is phpbb and the file i need to include is HTML so i used (Note, i did ../ back out to the banners root, its not a matter of my file not being found.
Im assuming that when including the scope is different. How would i correctly accomplish this include?
Banner.php
<?php
require("../mysql.inc.php");
check_get($tp, "tp");
$tp = intval($tp);
$link = sql_connect();
$result = sql_query($link, "SELECT COUNT(*) FROM online_count");
if (!$result) {
echo "Database error.<br>\n";
exit;
}
list($total) = mysql_fetch_row($result);
mysql_free_result($result);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<link rel="stylesheet" type="text/css" href="menu_css.css" media="screen"/>
</head>
<body>
<div class="menucenter">
<div class="Online"> <? echo"$total" ?> Online</div>
</body>
</html>
mysql.inc.php
<?php
$SQLhost = "****.db.****.hostedresource.com";
$SQLport = "3306";
$SQLuser = "****";
$SQLpass = "****";
$SQLdb = "****";
function sql_connect()
{
global $SQLhost, $SQLport, $SQLdb, $SQLuser, $SQLpass;
if ($SQLport != "")
$link = #mysql_connect("$SQLhost:$SQLport","$SQLuser","$SQLpass");
else
$link = #mysql_connect("$SQLhost","$SQLuser","$SQLpass");
if (!$link) {
echo "Database access error ".mysql_errno().": ".mysql_error()."\n";
die();
}
$result = mysql_select_db("$SQLdb");
if (!$result) {
echo "Error ".mysql_errno($link)." selecting database '$SQLdb': ".mysql_error($link)."\n";
die();
}
return $link;
}
function sql_query($link, $query)
{
global $SQLhost, $SQLport, $SQLdb, $SQLuser, $SQLpass;
$result = mysql_query("$query", $link);
if (!$result) {
echo "Error ".mysql_errno($link).": ".mysql_error($link)."\n";
die();
}
return $result;
}
function check_get(&$store, $val)
{
$magic = get_magic_quotes_gpc();
if (isset($_POST["$val"])) {
if ($magic)
$store = stripslashes($_POST["$val"]);
else
$store = $_POST["$val"];
}
else if (isset($_GET["$val"])) {
if ($magic)
$store = stripslashes($_GET["$val"]);
else
$store = $_GET["$val"];
}
}
?>
#Craig, there is a possibility that the include file contains other includes which are not getting the right path. Can you paste some codes of the include file for us to validate the error ?
EDIT:
You have a missing quote at the end of the query.
$result = sql_query($link, "SELECT COUNT(*) FROM online_count);
It should be
$result = sql_query($link, "SELECT COUNT(*) FROM online_count");
EDIT:
You have a problem with the quotes. See you check_get function. $val is a variable and you dont need quotes around it. Check the below code.
if (isset($_POST[$val])) {
if ($magic)
$store = stripslashes($_POST[$val]);
else
$store = $_POST[$val];
}
else if (isset($_GET[$val])) {
if ($magic)
$store = stripslashes($_GET[$val]);
else
$store = $_GET[$val];
}
EDIT:
Also remove the quotes from $query:
$result = mysql_query($query, $link);
First things first:
Remove the # from your mysql statements and see if you are getting any other errors related to variables or so. You should not suppress errors while debugging.
Try printing the host, port, user and password variables inside the sql_connect() function and see if you are getting the correct values in your function.
If you have access to your server, check if /var/lib/mysql/mysql.sock exists, and has sufficient permissions.
srwxrwxrwx 1 mysql mysql 0 Sep 21 05:50 /var/lib/mysql/mysql.sock
If all is well till this point, you might want to troubleshoot your MySQL service further. A restart would help flush the connections, if that is the issue. Check a similar thread in SO too.

create db and user mysql and set privileges php [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Is there a way to create a new MySQL database, a new MySQL user and give the new user privileges on the new database all using PHP?
You could do something like this:
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();
You may look at the MySQL documentation on GRANT and CREATE USER
Yes, as all these actions can be performed by regular SQL queries.
However, I'd refrain from running PHP scripts with database connection from root user.
If you are hosting your project on CPanel, then the mysql_query method will not work to create databases, users, and to grant permissions.
You have to use the XML Api for 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'));
?>
Download xmlapi.php from here, or simply search on google for it.
This is what worked for me perfectly.
i will suggest you to use phpmyadmin.
you need to do steps:
open phpmyadmin
go to admin section
hit on add user account
put user name and password
set privileges
hit the [ go ]button
that's all
see in action on youtube [ click here ]
in case if you want to know more about phpMyadmin go with official
but if there is any special reason to do so with php the here is the sql commend
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
open PHP myadmin or MySql workbench go to query window then run below query
CREATE USER 'username'#'localhost' IDENTIFIED BY 'password';
GRANT ALL ON db1.* TO 'username'#'localhost'"
<!--
Go to setup on line 48
Created by kierzo#kierzo.com
-->
<!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 kierzo#kierzo.com
//
// 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 $databasename#localhost";
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>";
?>

Categories