How to create a new mySQL database user from php - php

I was wondering if there was a way to create a new user for my MySQL Database? I'm trying to add basic log-in functionality that will allow the user to connect to database. If user has no account, then I want to create a new one. This is what I have so far:
<html>
<head>
<title>Test</title>
</head>
<body>
<?php
$username = "root";
$password = "root";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
$selected = mysql_select_db("contactsDB",$dbhandle)
or die("Could not select examples");
echo "Found contacts DB";
?>
</body>
Everything connects properly, but now, instead of having to type in the username and password (root), I want user to type their username and password. Again, if they don't have one, then I want to create a new one.

You need atleast one admin account to create a user with less privilege.
Please refer to
create db and user mysql and set privileges php
which is a good reference.

This is perfectly possible, but one thing I would stay clear of is logging in as root to do these commands.
With that in mind a method similar to this may work.
mysql_connect('localhost', 'user', password);
mysql_query("CREATE USER 'username'#'localhost' IDENTIFIED BY 'password';");
mysql_query("GRANT ALL ON db1.* TO 'username'#'localhost'");
mysql_close();
If you have a dedicated database for these new users, you can easily assign it then.

Related

Does a PHP file that attempts to connect to a database have to exist on the same server as the DB?

For example, when trying to connect to server xy.xy.xyz.xyz like below, does the script have to exist on that server to work?
<?php
$servername = "xy.xy.xyz.xyz";
$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";
?>
No it doesn't. The DB server has to be configured to allow remote connections though.
You can check this for further details for MySQL.
No, what's most likely happening is that your MySQL database isn't allowing users to sign in if they are trying to access it from an outside IP address.
Run the following command through MySQL
SELECT *
FROM information_schema.user_privileges
WHERE GRANTEE LIKE '%username%';
Change the username value to whatever the actual user name value is. If you're seeing a bunch of rows where the GRANTEE column is 'username'#'localhost' and nothing that looks like 'username'#'%', then your user is being limited to only localhost (same machine) access.
If you want to grant your user non-local access, you can use the following:
GRANT ALL PRIVILEGES
ON mydatabasename.*
TO 'username'#'%'
IDENTIFIED BY 'mypassword'
In the above, % means my user can connect from anywhere. This example grants all administrator rights to your user, but you can change that if you wish.

Can't get my PHP document to connect to my xampp server

I am very new to php, and am sorry if this question turns out to be too vague, but if there is any other information that you need from me let me know.
Anyway, basically what my problem is I have some simple php code that should call die() if it can't connect to the xampp server I have set up, however, even if I put in invalid info for the server or user it prints Successful. I really don't know where to go with this, so if anyone has any suggestions that would be great.
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
if ( !mysql_connect($dbhost, $dbuser, $dbpass) )
{
die(mysql_error());
}
else
echo 'Succesful';
?>
Ok for some reason it was just not working with the root user, so I created a new user who required a password and apparently that connected like it was supposed to. Thanks everyone for the answers.
Your code is correct pistolpete333. For your root user issue, that your not able to connect with root user you can check below file for your phpmyadmin configuration
C:\wamp\apps\phpmyadmin3.5.1\config.inc.php.
In above file you can check your host, username and password of phpmyadmin.
I have found that when trying to connect php to an xampp server there are usually only a few things that could cause the issue you are having.
1. mySQL service is not running
2. no specific database is selected to try to access
3. user does not exist in phpmyadmin.
When you pick a user to connect php to mySQL with you should always make sure that a password is set, that is usually the thing people miss. You can use root if you create another instance of it in the user list and require a password, or you can add a password to the root user already in the list, but the best option is to create a new custom user that only has access to the database you want to access with your php and make sure it has a password required. (make sure any user you use can connect with localhost; root can by default and I think most newly created users can as well).
Below is the php I use for websites I design that need php to access a DB.
<?php
// This configures the variables for database access
$dbhost = 'localhost';
$dbuser = '????';
$dbpass = '????';
$dbname = '????';
// This will connect to the server and then the correct database
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
mysql_select_db($dbname);
?>
This is working because you have specified valid username, host and password to mysql. If you specify wrong password, you get mysql error. This code works and connects to the mysql server though you have not selected any database.
Try this code instead
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$link = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$link) {
die('Not connected : ' . mysql_error());
}
// make foo the current db
$db_selected = mysql_select_db('foo', $link); //foo is your database name
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
?>

php script automatically creating mysql database?

does anyone know if there's a script out there that will create a mysql database automatically instead of having to go into cpanel and create a database, username and password manually?
thanks
You cannot create a username and password unless you log in yourself with a user with a higher level. That's usually the root. Creating database is a breeze after using the username and password with sufficient privileges.
<?php
$dsn = $dsn = "mysql:host=localhost";
$pdo = new PDO($dsn,"root","");
//Creation of user "user_name"
$pdo->query("CREATE USER 'user_name'#'%' IDENTIFIED BY 'pass_word';");
//Creation of database "new_db"
$pdo->query("CREATE DATABASE `new_db`;");
//Adding all privileges on our newly created database
$pdo->query("GRANT ALL PRIVILEGES on `new_db`.* TO 'user_name'#'%';");
?>
In this script, I assumed your root user is called "root" and its password is empty if that's not the case, change line 4 to match.
you cannot create new user without logging in.
You can create database with root account or user with privileges
<?php
mysql_connect("localhost", "root", "gm123") or die(mysql_error());
mysql_query("CREATE DATABASE cat") or die(mysql_error());
mysql_select_db("cat") or die(mysql_error());
mysql_query("CREATE TABLE user(username varchar(20), password varchar(20), permission varchar(20))") or die(mysql_error());
mysql_query("INSERT INTO user(username,password,permission) VALUES('gm','311807','admin')") or die(mysql_error());
mysql_query("CREATE TABLE cattbl(id INT NOT NULL PRIMARY KEY ,name VARCHAR(30),roll INT NOT NULL,technology VARCHAR(30),semister VARCHAR(30),shift VARCHAR(30),bdate varchar(30),cell VARCHAR(30),address VARCHAR(30),picture LONGBLOB)") or die(mysql_error());
header("Location: index.php");
?>
you may try this for your problem
i have just been doing this on my project
the actual answer is you can but it's a little complicated.
Cpanel doesnt allow you to use the normal "CREATE DATABASE 'mydbname';" in a php script to create a new database.
the only way you can do it is via logging on to your cpanel, going through the database wizard and creating a new one. Up until now you have probably been doing this manually each time.
this can been done with a php script but you have to use an api - which kind of goes through those same actions but automatically. You have to give the api your cpanel username and cpanel password.
just follow the answer to this question
Create cpanel database through php script
hope that helps
require_once 'database.php' add this line of code your index.php
$servername = 'localhost';
$username= 'root';
$password ='';
$conn = new mysqli($servername,$username,$password);
if($conn->connect_error)
{
die("Connection Failed !" . $conn->connect_error());
}
else
{
$sql = "CREATE DATABASE test_employee";
if($conn->query($sql)== TRUE )
{
echo "Database Created Successfully";
}
}
You definitely can! You can use PHP.
First you need to connect to the database. Then you need to run a SQL query on that database that creates the database. (which is essentially what cpanel does)
EDIT: Updated since my_sql is deprecated
Heres a stackoverflow post on how to do it...
Can I create a database using PDO in PHP

Can't select database table even though the code is right

I am trying to display a list of my vbulliten threads on a non-vbulliten portion of my site. However I can't select the vbulliten database:
<?php
$host = "localhost";
$user = "my username";
$pass = "my password";
$dbname = "tableprefix_forum";
mysql_connect($host, $user, $pass) or die ("Could not connect to database server.");
mysql_select_db($dbname) or die ("Could not select database.");
?>
I am substituting some things here in this example but all my credentials are correct including my db server username, password and forum db name. So what is the problem? Is it due to some internal security feature in vbulliten, does this system not allow you to connect to it's db if the page trying to connect to it is a non-vbulliten page?
Vbulletin has NO control over the permissions given by the server. But you do need to make sure that the user/pass you are using has been granted permission to access the database you are requesting.

How do I connect to mysql from php?

I'm working through examples from a book on php/mysql development.
I'm working on a linux/apache environment.
I've set up a database and a user. I attempt to connect with this line of code:
$db_server = mysql_connect($db_hostname, $db_username, $db_password);
I get this error:
Warning: mysql_connect()
[function.mysql-connect]: Access
denied for user 'www-data'#'localhost'
(using password: YES) in
/var/www/hosts/dj/connect.php on line
3 unable to connect to database:
Access denied for user
'www-data'#'localhost' (using
password: YES)
I can only guess what is happening here:
I think www-data is a username for apache. Upon the database connection, the credentials being passed in to mysql are not those of my database user, but rather apache's own credentials. Is that what is happening here?
How do I pass in the credentials I've defined for my user ?
edit:
By the way - I do have credentials in the variables $db_hostname, $db_username, $db_password.
they are passed in by another file using require_once. If that file can't be found, then I get an error. So, I know that my username and password are being used by my script.
Both my scripts can be seen here:
http://pastebin.com/MUneLEib
#
Solved:
Thanks guys.
A couple of you pointed out that I had coded carelessy.
Also, I was particularly pleased by Neo's answer: he told me why the username of the owner of the apache process was being used.
:)
I just looked at your code! The variable with the username is $database_username but
you are using $db_username.. Change your code to:
$db_server = mysql_connect($db_hostname, $database_username, $db_password);
or you could change the line with username with:
$db_username='[your mysql user]';//or the username you created
When you don't pass anything it will be the user mysql assumes but it will not get the password so if you hadn't defined $db_password it would say: (using password:NO)
you set $database_username with you user but you are passing $db_username which is not set so the user is the linux username as default when nothing is passed with the password for the mysql user! Since there is no mysql user with that password or privileges or even with that name you are not given access!
That user is www-data which is as you guessed an apache user assigned to client-side requests!
In your login.php you use the variable $database_username, but in your connection function you use $db_username. Try matching them up.
The username goes into $db_username, and the password goes into $db_password.
All these other answers are so presumptuous, as if you don't know that $db_username means database username and same for password.
The error says that you've specified an username and password. You just specified the wrong ones. You need to use the username and password of MySQL, NOT the system username/password combination, so no, this will not be www-data. This may be root and some password, but again, these credentials are specified within MySQL, and are not (necessarily) the same as the system users and passwords.
Your MySQL installation should have a root user with a default password (which you should promptly change). There are several options: you can add an user via the MySQL command line or use an interface like cPanel or Webmin if your provider has something like this; I've used both of these and they both have easy interfaces to add new MySQL users and assign them privileges.
Also just a tip: I typically create one user per database and give the user full privileges on the database, and then use that user with the application linked to the database.
And then of course, once you create a MySQL user account and give it privileges on your web app's database, fill in that username and password into your script.
<?php
$dbhost = 'localhost';
$dbuser = 'username';
$dbpass = 'password';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
?>
Make sure you actually assign your database login username and password to those variables before you try to connect. For example, before the line with mysql_connect():
$db_username = 'myuser';
$db_password = 'mypass123';
I'd recommend you go through a tutorial regarding MySQL and PHP before trying to go any further - just so you understand how it all works.
Try this one:
http://www.tizag.com/mysqlTutorial/mysqlconnection.php
Also, documentation is your friend:
http://php.net/manual/en/function.mysql-connect.php
The error given could mean that the privilege has not been granted, or perhaps the password is incorrect. Check that user is created and granted access, or just issue this to be sure it set to allow access on the mysql server.
$ mysql -u root -p
password:
(blah blah blah from server)
GRANT ALL PRIVILEGES ON db_base.* TO 'db username'#'localhost' IDENTIFIED BY 'some password';
If all privileges is too much, consider giving only the basic permissions needed:
GRANT SELECT,UPDATE,DELETE ON db_base.* TO 'db username'#'localhost' IDENTIFIED BY 'some password';
By the way, the server response to this statement on success is Query OK, 0 rows affected.
Your code is correct, it is saying your password is incorrect so your mysql database is rejecting the mysql connection. If you are using xampp use:
localhost
as hostname &
root
as username & in xampp there is no password so it would be
$password = ""; then $dblink = new mysqli($hostname, $dbuser, $password, $dbname);
so you can set your vars like this
<?php
$hostname = "localhost";
$dbuser = "root";
$password = ""; // means there is no password to the database
$dbname = "test"
?>
Conclusion :
if you get this as your message -
Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'www-data'#'localhost' (using password: YES) in /var/www/hosts/dj/connect.php on line 3 unable to connect to database: Access denied for user 'www-data'#'localhost' (using password: YES)
It means the password you entered is wrong or there is no password.
Stop using mysql_connect()!
You should not use this or other related functions related to this extension.
It's depreciated and removed in PHP 7.0.0 and beyond.
An alternative is using PDO or MySQLi.
Below is an example script for connecting to MySQL using PDO:
<?php
/* Connect to a MySQL database using driver invocation */
/* DSN options:
http://php.net/manual/en/ref.pdo-mysql.connection.php
Error handling options:
http://php.net/manual/en/pdo.error-handling.php
Learn how to secure against SQL injection attacks:
http://php.net/manual/en/pdo.prepared-statements.php
*/
$user = 'myusername';
$pass = 'mypassword';
$host = 'localhost';
$mydb = 'mydatabase';
$dsn = "mysql:dbname=$mydb;host=$host";
try {
$dbh = new PDO($dsn, $user, $pass);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>

Categories