PHP code doesn't create the database - php

In my web application, it has a self installing functionality so, after it is copied to the server, you just need to run the install.php file which has the following PHP code.
define("DB_SERVER","localhost");
define("DB_USER","db_user");
define("DB_PASS","pass");
//create mysql connection
$connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS);
if(mysqli_connect_errno()){
die("Connection Error");
}else{
echo "MySQL Connection Successful!";
}
//create database if not exists
$sql = "CREATE DATABASE equiz";
$mysqlQuery = mysqli_query($connection, $sql);
if($mysqlQuery){
echo "Database Created Successfully";
}else{
die("Database Not Created!");
}
In the localhost, this works perfectly fine. But, when this is moved to the server, it gives me this error
Access denied for user 'db_user'#'localhost' to database 'equiz'
I had created the user db_user in advance along with another database and I'm sure he was granted with all the permissions. But I'm not sure if those permissions were for that particular database only.
Anyway any clue for this error ? I know little bit PHP but very new to real world web servers.

The key here is:
Access denied for user 'db_user'#'localhost' to database 'equiz'
If it's your localhost, then probably you gotten phpMyAdmin installed. You need to grant access rights to your db_user. How to do this, there's explicit manual:
http://docs.phpmyadmin.net/en/latest/privileges.html
You also can do it manually, if you don't have phpMyAdmin installed, reference the official MySQL manual, or tutorials

You need to set privilege for that user:
GRANT INSERT, SELECT, DELETE, UPDATE ON database.* TO 'db_user'#'localhost' IDENTIFIED BY 'password';
Then try running your code.
If the above does not work out try creating the user will all rights:
CREATE USER 'user_name'#'localhost' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON * . * TO 'user_name'#'localhost';
FLUSH PRIVILEGES;
To create using PHP:
//Creation of user "user_name"
$mysqli->("CREATE USER 'user_name'#'%' IDENTIFIED BY 'pass_word';");
//Creation of database "new_db"
$mysqli->("CREATE DATABASE `new_db`;");
//Adding all privileges on our newly created database
$mysqli->("GRANT ALL PRIVILEGES on `new_db`.* TO 'user_name'#'%';");
Update:
Connect to database
// localhost <==> user_name <==> password <==> database
$mysqli = new mysqli("localhost", "user_id", "passwlrd", "db_name");
/* check connection */
if ($mysqli->connect_errno)
{
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}

Related

Why can't access to especific DB using PDO, but can using mysqli without DB name? (usign devserver/phpmyadmin)?

I install easyphp/devserver (v17.0) in a windows 10 x64 machine.
Working with tables and testing to store remote data with simple php files (very new with DataBases).
I'm trying to setup an access to my DB for my project (preferably using PDO).
Setup all database through mysql commands:
CREATE database arduDB;
CREATE USER 'Atmega'#'localhost';
GRANT USAGE on *.* to 'Atmega'#'localhost';
GRANT ALL PRIVILEGES ON arduDB.* TO 'Atmega'#'localhost';
CREATE USER 'Atmega'#'%';
GRANT USAGE on *.* to 'Atmega'#'%';
GRANT ALL PRIVILEGES ON arduDB.* TO 'Atmega'#'%';
FLUSH PRIVILEGES;
All fine up here.
But can't access to my DB (arduDB) using PDO, but can using MYSQLI without using DB name 'arduDB'.
I deleted '' (Any) users from phpmyadmin, but still can't access using PDO.
Searched and reading all day about this issue, but can't find a reason why happen this.
As well I create another user with a password, but can't access using PDO to DB neither.
It seems that phpmyadmin can't relate the permissions of the DBs,
edited
This 'add.php', without using 'arduDB' name give access through MYSQLI:
<?php
$servername = "localhost";
$username = "Atmega";
// Create connection
$conn = new mysqli($servername, $username);
// Check connection
if ($conn->connect_error) {
die("Failed: " . $conn->connect_error);
}
echo "Connected!!!";
?>
shows "Connected" in web browser. But same error if I try to use arduDB argument.
But when I use PDO, indicating arduDB database, I can't access to my DB.
<?php
$servername = "localhost";
$username = "Atmega";
try {
$conn = new PDO("mysql:host=$servername;dbname=arduDB", $username);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected!!!";
}
catch(PDOException $e)
{
echo "Failed: " . $e->getMessage();
}
?>
SQLSTATE[HY000] [1044] Access denied for user ''#'localhost' to database 'ardudb'
or
SQLSTATE[HY000] [1044] Access denied for user 'Atmega'#'localhost' to database 'ardudb'
Please, what can I need to configure or use in my code to grant access to a specific DB using PDO in my project?
Finlay I found the response.
Like André Verwijs says in his post, phpmyadmins use "unix_socket" to store user passwords in 'mysql' db. This is the motive that even if create or change password for any user, in 'User accounts' section of phpmyadmin always appears "NO" in PASSWORD COLUMN.
To solve this André Verwijs suggests do this in mysql console:
use mysql;
SELECT user, plugin FROM user;
UPDATE user SET plugin="mysql_native_password";
update user set authentication_string=password('USE-HERE-PASSWORD'), plugin='mysql_native_password' where user='Atmega';
FLUSH PRIVILEGES;
With this phpmyadmin will use plugin "mysql_native_password" for passwords in mysql DB. And now can access to my DB whit correct user and password (or without password).

Access denied to mySQL database using PHP

So I've been trying to solve this problem for a couple of hours now. And I have to make something clear.
I can access the mySQL database from terminal using
mysql -u root
I can also access the database from mySQL workbench
My root user on mySQL has no password
Now my code online is pretty simple. It is PHP calling the mysqli
<?php
$database = "myDatabase";
// Create new connection
$conn = new mysqli("localhost", "root", "", $database);
if ($conn -> connect_error) {
die ("Something went wrong: " . $conn -> connect_error);
} else {
echo "It works";
}
?>
Now I always get the error code
Something went wrong: Access denied for user 'root'#'localhost' (using password: NO)
If I could get any help that would be greatly appreaciated. I've already tried to grant access but I think I'm doing it wrong.
mysqli_connect may be interpreting the empty password as no password at all
using password: NO
Either try to set a password for the root user, or create a new user with a password. And via Tripp Kinetics comment, make sure the permissions are set properly for the new user.

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.

Connect via PHP to MySQL Database created using cpanel

I have a database and database user created via cpanel as below:
database name: test_database
database user: test_user
I am trying to connect to this database on the same server via a php script below:
<?php
$servername = "localhost";
$username = "test_user_test_database";
$password = "test";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
?>
However I end up with:
Warning: mysqli_connect(): (28000/1045): Access denied for user 'test_user_test_database'#'localhost' (using password: YES) in /home/driver/public_html/login/connect.php on line 7
Connection failed: Access denied for user 'test_user_test_database'#'localhost' (using password: YES)
Is the issue down to having an underscore in the username and database name? Or is there a way round this? I would much rather keep the username and database name as they are so wanted to check if there is any other way round it
Underscores are fine for naming.
mysqli_connect takes the database name as the 4th argument. Try adding your database name.
Finally, I seem to remember cPanel using some sort of automatic prefixes or something... double-check your database credentials if it's still not working.
You'll also have to add the user and the user permissions on that database.

MySQL login error warning

I'm getting this login error: Warning: mysqli::mysqli() [mysqli.mysqli]: (28000/1045): Access denied for user 'user'#client-ip' (using password: YES) in.
This happens no matter what I set in Cpanel. I've reset the passwords, created new users with all privileges.
I'm not that familiar with Cpanel but have created and reset user passwords for db users.
Using Cpanel... Do not have hosting access. Just FTP Access and access to Cpanel / PhpMyAdmin
I have looked and looked and it only seems that this could be an install problem with the permissions table or something of the sort... https://dev.mysql.com/doc/refman/5.1/en/access-denied.html
Not sure if I can access the console.
Here is my php for reference sake:
// try connect to the MySQL database
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
// var to check for duplicate txn - default false
$exists = false;
// check connection to database
if ($mysqli->connect_errno) { // false - database doesn't exist
$error = $mysqli->connect_errno;
} else { // database exists
$res = $mysqli->query("SELECT * FROM paypal_txn_log WHERE txn_id = '$txn_id'");
$exists = $res->num_rows;
// doesn't exist insert transaction number entry
if (!$exists) {
$time = date('Y-m-d H:i:s');
$query = "INSERT INTO paypal_txn_log (txn_id, customer_email, datetime) VALUES ('$txn_id', '$payer_email', '$time')";
$mysqli->query($query);
$mysqli->close();
}
}
MYSQL makes a difference between local and remote users.
GRANT <some privileges> TO '<username>' ON <database>.<table> ...
Will only grant access local user that talk to mysql via sockets
GRANT <some privileges> TO '<username>'#'<some ip>' ON <database>.<table> ...
will allow a user connecting via TCP/IP from that ip
GRANT <some privileges> TO '<username>'#'%' ON <database>.<table> ...
will allow user to connect from every
on the mysql shell, you will have to run
FLUSH PRIVILEGES
to make changes done with grant effective
As far as cpanel and phpmyadmin goes (which cpal uses) , these frameworks do the last step automatically if you add a user.

Categories