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

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>";
?>

Related

read database through sql without admin login

I have a problem every time two or more users are connecting to my app.
This is my code:
<?php
session_start();
$servername = "localhost";
$username = "admin";
$password = "my password";
$dbname="my dbname";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully".'<br>';
if($_SESSION["connected"] == 1)
{echo "you are logged in";}
else { die("Please log in to access this page");
echo "not logged in";}
?>
<!DOCTYPE html>
<html>
<head>
<title>Messages</title>
<meta http-equiv="refresh" content="1">
</head>
<body>
<?php
$sql="SELECT * FROM `mesaje` where reciever='all' order by data desc";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
{
if($row["sender"]==$_SESSION["username"])
echo '<div style="background-color:blue;" align="right">';
else echo '<div style="background-color:black;" align="left">';
echo '<p style="color:white;">'.$row["mesaj"]."</p></div>";
} }}
?>
</body>
</html>
When I am the only user connected, there is no problem, everything is alright.
when 2 or more users connect, they receive this error:
WARNING: mysqli_construct():MySQL server has gone away
I think that this is because they are more users logged in with the same admin account (maybe I am wrong)
Is there any way to connect to the database and only read it using sql without admin login? Or any other solution to the problem, please!
I am new to SQL
The status report that you get on your phone would make me think, that the server can't handle the second login. What are you hosting it on?
If you think that it's because the two admins, then try create a guest login and connect your user to the db with that.
If all doesn't help, create a login system, that adds a little table with users and so on.

Why am I getting an access denied error when connecting to MySQL db from php page

EDIT: I found the problem. The connection problem was located on the other page I was redirecting to, which had the wrong credentials, I'm an idiot.
This is my first time asking a quesiton in here, so bear with me.
I wanted to test to see whether or not I am able to insert data into my MySQL database through my .php page. Although I seemingly can't connect to my database, even though the username, password and so on are all correct. I use the same credentials, when I log on to the local instance trough MySQL Workbench.
The error i get in my browser says this:
Connection failed: Access denied for user 'root'#'localhost' (using password: YES)
Also this is my first time coding php, so the code is probably littered with errors, feel free to point them out.
Here's my code:
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
function prepareInput($input){
$input = trim($input);
$input = stripslashes($input);
$input = htmlspecialchars($input);
return $input;
}
$servername = "localhost";
$username = "root";
$password = "1234";
$dbname = "praktikdb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//---------------------------------------
$username1 = $password1 = "";
$errUsername = $errPassword = "";
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(empty($_POST["username"])){
$errUsername = "Username is required";
}
else{
$username1 = prepareInput($_POST["username"]);
}
if(empty($_POST["password"])){
$errPassword = "Password is required";
}
else{
$password1 = prepareInput($_POST["password"]);
}
$sql = "INSERT INTO users (username, password) VALUES('$username1', '$password1')";
$result = $conn->query($sql);
if(!$result) die("Something went wrong". $conn->error);
$result->close();
$conn->close();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Registration</title>
</head>
<body>
<form action="login.php" method="post">
Username: <input type="text" name="username">
<span class="error"> <?php echo $errUsername?></span>
<br>
Password: <input type="text" name="password">
<span class="error"> <?php echo $errPassword?></span>
<br>
<input type="submit" name="btnRegister" name="Register"/>
</form>
</body>
</html>
Your code is giving you a credentials problem (detected by your "Check connection" piece of your code), and that is derived of the users configuration in your MySQL Workbench. You need to configure the user you will use for your PHP connection to MySQL, along with the password, and the server the user connecting will be limited to (in this case is the localhost), and the privileges your user will have.
Also, and this is just for connecting to your database (for now consider that you won't execute a SQL query in your code), you can check if the connection it's ok with just your username, the password and the server name.
<?php
/* $servername, $username and $password goes here */
$conn = new mysqli($servername, $username, $password);
if($conn->connect_error) {
die("Connection failed:" $conn->connect_error);
}
echo "Connection successful";
?>

identified by password in the grant query affecting irrelevant connection

In the code below there are 2 mysql connections, the issue is that the second connection gives a connection error if the password coming in from the form is anything but 123456.
Now, password coming in from the form should have nothing to do with the second connection because that password in for the new database that is made before the second conenction starts. The second connection is connecting to another database all together.
However, if i use the commented out $grantQ query, the second connection works fine. That means that the issue is got something to do with identified by '{$pass}' in the $grantQ query.
The identified by '{$pass}' query should only affect the new database that has been created. Why is it affecting the existing db that the second connection is connecting to?
please help .. sorry about the long summary !
<?php
if(isset($_POST['submit'])){
// SUPER CONNECTION
$maindb_db = "little_maindb";
$maindb_server = "localhost";
$maindb_username = "admin#littlesidegym.com";
$maindb_password = "123456";//
$conn = new mysqli($maindb_server, $maindb_username, $maindb_password, $maindb_db);
if ($conn->connect_error) {
die($contact_cus_supp);
}
//NAME OF DB FROM POST - CUSTOMER VIEW
$new_dbname = mysqli_real_escape_string($conn, $_POST['db_name']);
$new_pass = mysqli_real_escape_string($conn, $_POST['pass']);
// CREATING DATABASE
$sql = "CREATE DATABASE IF NOT EXISTS $new_dbname ";
if (!mysqli_query($conn, $sql)) {
mysqli_close($conn);
exit();
}
$host = "localhost";
$user = $_SESSION['sess_email'];
$flush_pri = "FLUSH PRIVILEGES";
$pass = $new_pass;
// GRANT USER PRIVILEGES
echo $current_project;
$grantQ = "GRANT ALL PRIVILEGES ON " . $new_dbname . ".* TO '{$user}'#'{$host}' identified by '{$pass}'";
//$grantQ = "GRANT ALL PRIVILEGES ON " . $new_dbname . ".* TO '{$user}'#'{$host}'";
if(!mysqli_query($conn,$grantQ)){
mysqli_close($conn);
exit();
}
if(!mysqli_query($conn,$flush_pri)){
mysqli_close($conn);
exit();
}
// SUPER CONNECTION CLOSE
mysqli_close($conn);
// ALTOGETHER A DIFFERENT CONNECTION
$secdb_db = "little_userdb";
$secdb_server = "localhost";
$secdb_username = "user#littlesidegym.com";
$secdb_password = "123456";//
$conn = new mysqli($secdb_server, $secdb_username, $secdb_password, $secdb_db);
if ($conn->connect_error) {
die($contact_cus_supp);
}
echo "HELLO WORLD";
?>
// FORM
echo '<table>';
echo '<form action="create_project.php" method="POST" id = "myform" name = "myform" >';
echo '<tr><th></th></tr><tr><td><input type = "text" value="" name = "db_name" class = "req alphanums" placeholder = "DB Name" ><td></tr>';
echo '<tr><th></th></tr><tr><td><input type = "password" value="" name = "pass" class = "req" placeholder = "Password" ><td></tr>';
echo '<tr><th></th></tr><tr><td><div id = "submit"><input type="submit" id = "submit" name = "submit" value = "Create Project"></div><td></tr>';
echo '</form>';
echo '</table>';
You are using the same user name for newly created database and for accessing little_userdb, thus changing its password each time.
In mysql user is identified by name and hostname mask (mysql looks for first match). So your code changes password for existing user and grants him access to the new db.

What password and username do I use for mysql_connect()?

Okay so as you will probably be able to tell but, I am pretty new to MySQL and PHP and I have ran into a problem.. In my connect.php, which connects to the server, I don't know if my password and username along with the port are right. Now the reason it says port 8080 is because one of my other web development programs was using port 80 so I went in to the Apache files and changed to port, so now when I log into phpMyAdmin I have to type localhost:8080. I don't know if that has to do with mysql_connect, also I checked on phpMyAdmin and it says my username is root and my password is empty. Does the empty password mess with MySQL_connect()? Thanks, here's the code:
connect.php:
<?php
//This file allows me to easily connect to my database
mysql_connect("localhost:8080", "root", "");//connects to database, params are ("servername", "username", "password");
mysql_select_db("membersystem");//selects the table from db
?>
login.php:
<?php
error_reporting (E_ALL ^ E_NOTICE);//saves us from getting undefined index error
session_start();//makes it a sesion based system
?>
<!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 http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Login</title>
</head>
<body>
<!--the action='./login.php' tells the page where its gonna send the info, and the method='post' makes it so it dosent show the users personal info -->
<?php
$form = "<form action='./login.php' method='post'>
<table>
<tr>
<td>Username</td>
<td><input type='text' name='user'/></td>
</tr>
<tr>
<td>Password</td>
<td><input type='password' name='password'/></td>
</tr>
<tr>
<td></td>
<td><input type='submit' name='loginbtn' value='Login'/></td>
</tr>
</table>
</form>";
if($_POST['loginbtn']){//if loginbtn pressed
$user = $_POST['user'];//gets the username from text field from the form above
$password = $_POST['password'];//gets the password from text field from the form above
if($user){//checks if the username field from the form has been filled out
if($password){//checks if the password field from the form has been filled out
require("connect.php");//connects to db through connect.php
$password = md5(md5("gshgrYY665f".$password."gr76TH967G"));//encrypts the password
//echo "$password"; echos the hash for password (5f8b1a8d8f2471a2c7c17e0058873447 )
$query = mysql_query("SELECT * FROM users WHERE username='$user' ");//checks if the username is found in database
$numrows = mysql_num_rows($query);
if($numrows == 1){
$row = mysql_fetch_assoc($query);//gets the query associated with the php
$dbid = $row['id'];//gets the id from db
$dbuser = $row['username'];//gets the username from db
$dbpass = $row['password'];//gets the password from db
$dbactive= $row['active'];//gets the active value from db
if($password == $dbpass){
if($dbactive == 1){
//sets session info
$_SESSION['userid'] = $dbid;
$_SESSION['username'] = $dbuser;
echo "you have been logged in as <b>$dbuser</b>. <a href='./member.php'>Click here</a> to go to member page";
}
else
echo "You must activate your account to login. $form";
}
else
echo "You didnt enter the right pass. $form";
}
else
echo "The username you entered was not found. $form";
mysql_close();//closes connection
}
else
echo "You must enter your password. $form";
}
else
echo "You must enter your username. $form";
}
else
echo $form;
?>
</body>
</html>
You dont need to use 8080 simply use localhost because that port number is not related to mysql but related to webserver. Inorder to address the webserver only you need to use it like localhost:8080/project-name/
And dont use mysql_* methods. will get disappointed in future. Use mysqli
$con = new mysqli("localhost","root","","membersystem") or die('Connection failed');
$result = $con->query("Your query here");
or else you can use the same in procedural method with mysqli_* functions. But i prefer to go along with object oriented php.
Refer the documentation.
http://php.net/manual/en/book.mysqli.php
Make connection like
$conn=mysqli_connect("localhost","root","","membersystem");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
and w3schools link is http://www.w3schools.com/php/func_mysqli_select_db.asp

mysqli access denied (42000/1044) linux permissions?

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.

Categories