Rights INSERT PHPmyadmin MySQL - php

I have setup a basic table and connected a PHP file with the database. I can fetch data from the database by using SELECT. However, when I try to use UPDATE or INSERT INTO, I get the message:
"INSERT command denied to user ''#'localhost' for table 'table_data'".
When I try to use the query in PMA, i am able to insert data. But when i want to adjust user rights, it says i don't have the rights to do so. But when i use the SQL SHOW GRANTS, i receive:
"Grants for xxx#10.0.% GRANT USAGE ON . TO 'xxxl'#'10.0.%'
IDENTIFIED BY PASSWORD GRANT ALL PRIVILEGES ON
'database_name'.* TO 'xxx'#'10.0.%' WITH GRANT OPTION.
I am using the only MySQL account provided by my host so I assume it is the root user.
$servername = "mysql.domain_name.nl";
$username = 'xxx';
$password = 'xxx';
$conn = new mysqli($servername, $username, $password);`
$username = $_POST['username'];
$password = $_POST['password'];
$query = "INSERT INTO 'game'.'login_data' ('username', 'password') VALUES ('".$username."', '".$password."')";
$data = mysql_query ($query)or die(mysql_error());
Please help me to gain rights to be able to INSERT.

First you need to read up on using mysqli. Everything you need is here: http://php.net/manual/en/book.mysqli.php
You will see that you are missing 1 parameter from your $conn
Needs to be new mysqli('localhost', 'my_user', 'my_password', 'my_db');
$servername = "mysql.domain_name.nl";
$username = 'xxx';
$password = 'xxx';
$conn = new mysqli($servername, $username, $password, **add database**);
$username = $_POST['username'];
$password = $_POST['password'];
For the sake of security you want to use prepared statements.
Change it to the following:
if ($stmt = $conn->prepare("INSERT INTO `game`.`login_data` (username, password) VALUES (?, ?)")) {
$stmt->bind_param('ss', $username , $password );
// Execute the prepared query.
if (! $stmt->execute()) {
$stmt->close();
}
}
}
Of course this is not the way you should completely treat a user database. You want to be hashing passwords, storing salts etc. But for this question. The above should be enough.

I have tidied up your code, fixed the syntax errors, as well as switched the entire code to PDO.
MySQL is deprecated and MySQLi is open to SQL injection hacks, even with mysqli_real_escape_string!
<?php
$user = 'xxx';
$pass = 'xxx';
$conn = new PDO('mysql:host=localhost;dbname=mysql.domain_name.nl', $user, $pass);
$username = $_POST['username'];
$password = $_POST['password'];
$stmt = $conn->prepare("INSERT INTO `game`.`login_data` ('username', 'password') VALUES (:username, :password)");
$stmt->bindParam(':username', $username);
$stmt->bindParam(':password', $password);
$stmt->execute();
?>
For more information on PDO, consult the manual here: http://php.net/manual/en/book.pdo.php

Related

Data isn't sending from AndroidStudio to phpMyAdmin / 000webhost

I'm trying to create a basic Register and Log in Application by following this tutorial: https://www.youtube.com/watch?v=JQXfIidfFMo&t=193s and because the code in Android Studio has shown 0 Compile Errors I've decided not to put that here.
What's wrong
Many users have reported in the comments section both old and new that they could not get their information sent to their database so any help would be greatly appreciated. The user inputs their 'name', 'username', 'password', and 'age' to register and this information is to then sent to my database hosted on 000webhost. Everything has been followed to the T.
The name of the table is called 'user'.
Here is the code to my Login.php file
<?php
$con = mysqli_connect("localhost:3306","id7390457_user","abcd1234","id7390457_data");
$username = $_POST["username"];
$password = $_POST["password"];
$statement = mysqli_prepare($con, "SELECT * FROM user WHERE username = ? AND password = ?");
mysqli_stmt_bind_param($statement, "ssis", $username, $password);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement, $user_id, $name, $age, $username, $password);
$response = array();
$response["success"] = false;
while(mysqli_stmt_fetch($statement)){
$response["success"] = true;
$response["name"] = $name;
$response["age"] = $age;
$response["username"] = $username;
$response["password"] = $password;
}
echo json_encode($response);
?>
Here is the code to my Register.php file
<?php
$con = mysqli_connect("localhost", "id7390457_user", "abcd1234", "id7390457_data");
$name = $_POST["name"];
$age = $_POST["age"];
$username = $_POST["username"];
$password = $_POST["password"];
$statement = mysqli_prepare($con, "INSERT INTO user (name, age, username, password) VALUES (?, ?, ?, ?)");
mysqli_stmt_bind_param($statement, "ssis", $name, $age, $username, $password);
mysqli_stmt_execute($statement);
$response = array();
$response["success"] = true;
echo json_encode($response);
?>
I have been under the impression that the line
$con = mysqli_connect("localhost", "id7390457_user", "abcd1234", "id7390457_data");
Is followed by using ('hostname', 'username', 'password', 'nameofdatabase')
However as I am doing this from my Mac so my host is 'localhost'
My DB Name is: id7390457_data
My DB User is: id7390457_user
I've tried using 'localhost:3306'
I've tried just 'user' and 'data'
I've watched YouTube videos, visited websites in other languages and none have seemed to provide any advise.
I've deleted multiple databases starting from scratch but I still face the issue whereby my information isn't being sent to phpMyAdmin on 000webhost.
My webhost doesn't have an index.html page but I don't think that this would be the issue.
Thank you
Any help would mean the world to me. Thank you wish you well!
Hi and welcome to StackOverflow!
You are right, the mysqli_connect expects the host, user, pass and db name in that order, so if the database is running and the values are correct as you said, this looks OK.
However on this line, note the second argument ssis:
mysqli_stmt_bind_param($statement, "ssis", $name, $age, $username, $password);
It states the type of the parameters, s for string and i for integer. It looks like the order is messed up, because age is expected as a string and username as an integer. If you replace it with siss, I would expect it to work.
More info: https://secure.php.net/manual/en/mysqli-stmt.bind-param.php

Simple Login using mySQLi PHP error

I'm trying to create a simple login using mySQLi with PHP. I have everything set up using a variable $username and $password that holds the login information rather than using post from a form as I just want to get it working first before advancing to this and injection protection. So all in all if the variables match the table in the data base then it prints Logged In! otherwise it'll print Invalid username or password but every time I run this I get an error:
Error:
Warning: mysqli_query() expects parameter 1 to be mysqli, null given
<?
$dbhost = 'localhost';
$dbuser = 'xxxx';
$dbpass = 'xxxx';
$dbname = 'xxxx';
$con = mysqli_connect($dbhost, $dbuser, $dbpass,$dbname);
$sql="SELECT email, pass FROM lg_user";
$username = 'Admin';
$password = "123qweQWE";
$query = "SELECT `user` FROM `lg_user` WHERE `user`='$username' AND `pass`='$password'";
var_dump($query);
if($query_run = mysqli_query($conn,$query)){
$query_num_rows = mysqli_num_rows($query_run);
if($query_num_rows == 0){
print("Invalid username or password");
}
else if($query_num_rows == 1){
print("Logged In!");
}
}
?>
Just to make my point that doing it the right way is not over complicated here you go.
$dbhost = 'localhost';
$dbuser = 'xxxx';
$dbpass = 'xxxx';
$dbname = 'xxxx';
$Pdo = new PDO("mysql:host={$dbhost};dbname={$dbname};charset=utf8", $dbuser, $dbpass);
$Pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$Pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$Pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$username = 'Admin';
$password = "123qweQWE"; //create a password with password_hash($password, PASSWORD_DEFAULT);
$stmt = $Pdo->prepare("SELECT `user`,`pass` FROM `lg_user` WHERE `user`=:username"); //don't pull user by looking for the password.
$stmt->execute([':username' => $username]);
if($stmt->rowCount() == 1){
$row = $stmt->fetch();
if(password_verify($password, $row['pass'])){
//verify does not require hashing the incoming password (assuming password was made with password_hash)
print("Logged In!");
}else{
print("Invalid password");
}
}else{
print("Invalid username");
}
23 lines, 3 of which are optional ($Pdo->setAttribute). The original attempt 17 lines.
Both of these have at least 2 extra lines in (username/password canned data). So for 6 extra lines (3 of which are optional) We can do this the right way. Coincidentally the other 3 lines are here (separate error for password/username):
}else{
print("Invalid password");
}
So pretty much the same number of lines.
Major notes,
Do not check password by querying it.
Hashes are case sensitive, DB typically is not (unless you use UTF8_bin).
It's not a cryptologically secure evaluation of the hash
You can't tell if it's a bad password or a bad username
Use prepared statements.
Use PHP's built in password functions
Use PDO,
the OOP API for PDO is better
the fetch modes are far better than mysqli
the error handling is far better (with exception mode)
all this saves a lot of work in the long run (my opinion).
References:
http://php.net/manual/en/function.password-verify.php
http://php.net/manual/en/function.password-hash.php
http://php.net/manual/en/class.pdo.php
I would also strongly recommend making the username a unique index in the Database itself. This will give you 100% guarantee that usernames cannot be duplicated. It will also throw an exception with PDO, which is very easy to catch and report.

mysqli connection not working with mysqli_real_escape_string

I have a simple demo php scripts am trying out. i have been using the deprecated mysql_ extensions earlier, trying to migrate from that to mysqli_ is being overly buggy. when trying to use mysqli_real_escape_string php throws a variable not defined error cant seem to figure out why.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "bridgoo";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
//do stuff
}
// prepare and bind
$stmt = $conn->prepare("INSERT INTO bridgoo_users (username, email, password) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $username, $password, $email);
//generate password hash using blowfish algorithm
$password_hash = password_hash($_POST['password'], PASSWORD_BCRYPT, ["cost" => 9]);
$username = clean_input($_POST['username']);
$password = clean_input($password_hash);
$email = clean_input($_POST['email']);
function clean_input($input){
$input = htmlentities($input);
$input = htmlspecialchars($input,ENT_QUOTES);
$input = mysqli_real_escape_string($conn,$input);
return $input;
}
$stmt->execute();
$stmt->close();
$conn->close();
?>
php error Notice: Undefined variable: conn in C:\xampp\server1\htdocs\bridgoo\inc\register.php on line 24
The error about undefined variable $conn has to do with PHP variable scope, and other people have answered that.
But your code needs some other suggestions too.
You don't need to clean inputs at all if you use query parameters. That's the point of using query parameters: No need for mysqli_real_escape_string() because parameters are automatically safe.
In fact, you must not use mysqli_real_escape_string(), because your data will be inserted to your database literally with \' escaped apostrophes.
Simply put: SQL parameters and mysqli_real_escape_string() are mutually exclusive. Don't do both.
Also, it makes no sense to use htmlentities() or htmlspecialchars () at all for sanitizing SQL inputs, even if you use mysqli_real_escape_string() instead of parameters.
Those html-related functions are for HTML output only. They're very important for protecting your web app against XSS vulnerabilities, which is another unrelated web security risk you need to know about. But they're not needed for sanitizing SQL input.
Other comments:
It's confusing that you're re-using username and password variables for both the mysqli connection and the application data. There's no reason to re-use variables, they don't cost you anything.
Make sure the order of parameters in your INSERT matches the order of bind variables you pass to bind_param().
Always check the return value of prepare() and execute(). They return FALSE if they fail. If they fail, you must log the error and report to the user that the page didn't work.
I prefer to log the technical error message to the PHP error log
file, and report something more friendly to the user.
Get into the habit of keeping a window open to watch your PHP error log during development, it'll help you a lot.
Here's how I suggest you write your code:
<?php
$mysql_servername = "localhost";
$mysql_username = "root";
$mysql_password = "";
$mysql_dbname = "bridgoo";
$conn = new mysqli($mysql_servername, $mysql_username, $mysql_password, $mysql_dbname);
if ($conn->connect_error) {
error_log($conn->connect_error);
die("Sorry, a database error occurred.");
}
$stmt = $conn->prepare("
INSERT INTO bridgoo_users (username, password, email)
VALUES (?, ?, ?)");
if ($stmt === false) {
error_log($conn->error);
die("Sorry, a database error occurred.");
}
$stmt->bind_param("sss", $username, $password_hash, $email);
//generate password hash using blowfish algorithm
$password_hash = password_hash($_POST['password'], PASSWORD_BCRYPT, ["cost" => 9]);
$username = $_POST['username'];
$email = $_POST['email'];
if ($stmt->execute() === false) {
error_log($conn->error);
die("Sorry, a database error occurred.");
}
if ($stmt->affected_rows == 1) {
echo "Success!"
} else {
echo "Sorry, an unknown problem occurred, and your record was not saved."
}
Your clean_input function does not have access to your $conn variable, it lives in a different scope.
The easy solution would be to add the connection as a parameter to the function. Something like this:
<?php
...
$username = clean_input($_POST['username'], $conn);
$password = clean_input($password_hash, $conn);
$email = clean_input($_POST['email'], $conn);
function clean_input($input, $conn){
...
Wether that is the best or cleanest solution I'll leave in the middle, but it should work just fine.
You should pass $conn as parameter to your function clean_input;
$username = clean_input($conn, $_POST['username']);
$password = clean_input($conn, $password_hash);
$email = clean_input($conn, $_POST['email']);
function clean_input($conn, $input){
$input = htmlentities($input);
$input = htmlspecialchars($input,ENT_QUOTES);
$input = mysqli_real_escape_string($conn,$input);
return $input;
}

Establishing PHP connection with localhost server?

I am having an issue with connecting my PHP script to the database on my localhost server.
I have posted the code below, it is to enable user registration on the site.
The input boxes appear as they should when I run the code, but nothing updates to the database when I try and complete a sign up.
As a novice with PHP I don't know enough about it to spot any errors I might be making, or what they mean.
Any help on this subject would be appreciated as there is a lot of info about PHP online, but I would rather know what was causing this error in order to prevent it in the future.
Here are the errors appearing in the browser console:
Failed to load resource: the server responded with a status of 404 (Not Found)
ReferenceError: Can't find variable: $
And the UNIX socket code from MAMP (I don't know where this would fit in):
$user = 'root';
$password = 'root';
$db = 'inventory';
$socket = 'localhost:/Applications/MAMP/tmp/mysql/mysql.sock';
$link = mysql_connect(
$socket,
$user,
$password
);
$db_selected = mysql_select_db(
$db,
$link
);
And the PHP code:
//connect to database
$db = mysql_connect("localhost", "root", "", "authentication");
if (isset($_POST['register_btn'])) {
session_start();
$username =mysql_real_escape_string($_post['username']);
$email =mysql_real_escape_string($_post['email']);
$password =mysql_real_escape_string($_post['password']);
$password2 =mysql_real_escape_string($_post['password2']);
if ($password == $password2) {
//create user
$password = md5($password); //hash password before storing for security
$sql = "INSERT INTO users(username, email, password) VALUES('$username', '$email', '$password')";
mysql_query($db, $sql);
$_SESSION['message'] = "Find a Table";
$_SESSION['username'] = $username;
header("location: HomePage.html"); //redirect to homepage
}else{
$_SESSION['message'] = "Your passwords must match to proceed";
}
}
?>
Where to start? So many problems.
First off, you are using the OLD mysql functions which have been removed entirely in recent versions of PHP. Use the mysqli functions instead. The old functions like mysql_connect and mysql_query have been deprecated. You need to look for all occurrences of mysql_ in this code and think about replacing each command with its new counterpart.
You define this code to connect:
$user = 'root';
$password = 'root';
$db = 'inventory';
$socket = 'localhost:/Applications/MAMP/tmp/mysql/mysql.sock';
$link = mysql_connect(
$socket,
$user,
$password
);
$db_selected = mysql_select_db(
$db,
$link
);
and then you don't use the resulting connection -- even check if it worked. You should always check the value returned by mysqli_connect to see if it actually worked or if it returned FALSE. You reconnect again and don't bother checking to see if it worked:
//connect to database
$db = mysql_connect("localhost", "root", "", "authentication");
And in doing so, you redefine $db to something else.
Also, you run a query without checking whether it succeeded or not:
mysql_query($db, $sql);
$_SESSION['message'] = "Find a Table";
$_SESSION['username'] = $username;
header("location: HomePage.html"); //redirect to homepage
You should be checking the result of mysqli_query (not mysql_query as you have in your code) to see what it returned. It should be TRUE if the INSERT query worked.
And after you redirect, you fail to call exit, which means that all the code that follows your redirect attempt may end up actually executing anyway.

Trying to connect sql database in xampp

<?php
$host = 'localhost';
$user = 'root'
$password = '';
$db ='members';
$connection = mysqli_connect("localhost", "user", "password") or die("Unable to connect to the server!");
mysqli_select_db("members", $connection) or die("Couldn't connect to the database!");
I have installed xampp and create database named "members". I tried to connect it to phpmyadmin but didn't work. I try to google all the answers since three days but in vain. Please help me...
<?php
$host = 'localhost';
$user = 'root';
$password = '';
$db ='members';
$connection = mysqli_connect($host,$user,$password,$db);// you can select db separately as you did already
if($connection){
// do all your stuff that you want
}else{
echo "db connection error because of".mysqli_connect_error();
}
Are your credentials for username and password correct?
By default, the localhost has username = root and password as blank.
Also, what's the issue? Is it showing "Unable to connect to the server!"?
You are missing a semicolon after $user = 'root' and you are using a mixture of mysql_ and mysqli_. Also, you could select a table by passing a fourth argument to mysqli_connect()
$host = 'localhost';
$user = 'root';
$password = '';
$db ='members';
$connection = mysqli_connect($host,$user,$password,$db);// you can select db separately as you did already
if($connection){ echo "Connected Successfully";}else{ echo "Error connecting: . mysqli_connect_error()"; }
Use mysqli_ to do queries:
mysqli_query($connection, "INSERT INTO user_login (uname,upassword,email) VALUES ('$uname','$upassword','$email')");
I recommend you to use prepared statements to avoid SQL injection.
So the above query would look like:
$stmt->prepare("INSERT INTO user_login (uname,upassword,email) VALUES (?,?,?)");
$stmt->bind_param('sss', $uname, $upassword, $email);
$stmt->execute();

Categories