This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
mysql kill process is user dont got enought points PHP
i have a points system with user system where people can upgrade to [PRO] user with 50 points. When they register it automaticly write [user] down to my rights field. but now i want so after a'n action it check if they got 50 points and then replace [user] with [PRO] and then subtrac 50 points.
<?php
session_start();
//=============Configuring Server and Database=======
$host = 'localhost';
$user = 'root';
$password = '';
//=============Data Base Information=================
$database = 'login';
$conn = mysql_connect($host,$user,$password) or die('Server Information is not Correct'); //Establish Connection with Server
mysql_select_db($database,$conn) or die('Database Information is not correct');
//===============End Server Configuration============
//=============Starting Registration Script==========
$username = mysql_real_escape_string($_POST['txtusername']);
//=============To Encrypt Password===================
//============New Variable of Password is Now with an Encrypted Value========
$insert = "UPDATE `users` SET `points` = (`points`-50) WHERE `username` = '".$username."' and points > 50";
mysql_query($insert);
if (mysql_affected_rows() > 1)
{
// other codes
$insert = "UPDATE `users` SET `rights` = (`rights` [PRO]) WHERE `username` = '".$username."'";
mysql_query($insert);
header('location: succesupgrade.php');
}else{
echo "You don't have enough points to buy [PRO]";
}
?>
Again: i want so after people buy [PRO], the [user] get replaced with [PRO]. ANd then they lose 50 points. and if they dont got 50 points. echo says something.
Do it in one:
UPDATE `users`
SET `rights` = '[PRO]', points = points - 50
WHERE
`username` = 'somename'
AND points >= 50
AND rights != '[PRO]'
And just check whether you have an effected row or not. If they don't have enough points, it won't update, and neither will it when they already have the right. This avoids race conditions.
Related
This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 7 years ago.
I honestly can't see why this doesn't work. I have checked it several times even compared it to other examples I have done that does work. Please note that I have taken it down to the simplest form so there is no sql injection protection. That comes later.
//user real escape string to prevent SQL injection
$username = $_POST['username'];
$password = $_POST['password'];
//check if username and password is blank
if (!$username || !$password)
die ("Not all the fields were filled in");
//Server details
$host = 'localhost';
$user = 'tm_user';
$password = 'password';
//The database name
$database = 'TransportMe';
// Create connection
$con = new mysqli($host, $user, $password, $database);
// Check connection
if ($con->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//since user and password is not blank, find user info using the email and password entered by user
$sql= "SELECT * FROM Users WHERE 'email'='$username' AND 'password' = '$password';";
//Get the results
$result = $con->query($sql);
//Check if null
if ($result->num_rows == null)
die("Null");
use backticks for columns in your query like this
$sql= "SELECT * FROM Users WHERE `email` = '$username' AND `password` = '$password'";
Your query should be:
//since user and password is not blank, find user info using the email and password entered by user
$sql= "SELECT * FROM `Users` WHERE `email` = '{$username}' AND `password` = '{$password}';";
This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 8 years ago.
Ok so I am having some issues with a query. I am working to learn MySQLi as well so there may be some errors. I have a table named Authentication and in it, it has these columns
||id
||UserName
||Password
When running the query I am getting my username as the column name so it gives the unknown column error. I can not seem to see what is wrong with my code. Any help is appreciated.
<?php
// Report all errors
error_reporting(E_ALL);
session_start(); // Start PHP
// Get info sent to server from login form.
$my_username = $_POST['username'];
$my_password = $_POST['password'];
// MD5 Encrypt the password.
$my_password_md5 = md5($my_password);
// Connect to DB
$db = new MySQLi('localhost', 'user', 'password!', 'database');
if ($db->connect_error) {
$error = $db->connect_error;
}
//SQL query
$sql = <<<SQL
SELECT UserName
FROM `Authentication`
WHERE `username` = $my_username HAVING `username` = $my_password_md5
SQL;
$result = $db->query($sql) or die($db->error.__LINE__);
if($result = $db->query($sql))
$rows=mysqli_fetch_assoc($result);
// Count how many rows match that information.
$count=mysqli_num_rows($result);
// Check if there are any matches.
if($count==1)
{// If so, register $my_username, $my_password and redirect to the index page.
ini_set("session.gc_maxlifetime", "18000");
session_cache_expire(18000);
$cache_expire = session_cache_expire();
$_SESSION['username'] = $my_username;
$_SESSION['id'] = $rows['id'];
header("location:http://somesitegoeshere.com");
}
// If not, redirect back to the index page and provide an error.
else {
header("location:http://somesitgoeshere.com?err=1");
}
?>
$sql = <<<SQL
SELECT UserName
FROM `Authentication`
WHERE `username` = $my_username HAVING `username` = $my_password_md5
SQL;
You forgot to quote $my_username. so your query looks like WHERE 'username' = abcdefg HAVING...
Mysql thinks you're trying to compare to a column, put your username in quotes. Also put your password in quotes so it doesnt think your password is a column.
$sql = <<<SQL
SELECT UserName
FROM `Authentication`
WHERE `username` = "$my_username" HAVING `username` = "$my_password_md5"
SQL;
I want to check if the 'desig' (designation) of a user stored in user_info database, is 'gm' (G.M.) or not.
Currently, I have two users, one with 'desig' as 'gm' and the other as 'mgr', no matter who logs in, the 'gm.html' page always loads.
The correct working should be that if the desig is gm then only it should redirect to gm.html page. (members is a table in user_info db)
<?php
session_start();
if((isset($_SESSION['login']) && $_SESSION['login'] ==true)) {echo "";}
else{
header("location:login.html");}
$mysql_hostname = 'localhost';
$mysql_usrnm = 'root';
$mysql_pass = '';
$mysql_db = 'user_info';
$con = mysqli_connect($mysql_hostname, $mysql_usrnm, $mysql_pass, $mysql_db) or die('Cant connect to database');
mysqli_select_db($con,$mysql_db);
$result = mysqli_query($con, "SELECT desig FROM members WHERE desig='gm'");
if (!$result) {
printf("Error: %s\n", mysqli_error($con));
exit();
}
$desig = mysqli_fetch_array($result) or die("error");
if($desig!="gm")
{
$mysql_db1='customer';
$con1=mysqli_connect($mysql_hostname, $mysql_usrnm, $mysql_pass, $mysql_db1) or die("Connection died for your sins.");
echo "Connected";}
else
header("location:gm.html");
?>
Your code seems to be hard-coded to only return a GM?
$result = mysqli_query($con, "SELECT desig FROM members WHERE desig='gm'");
I am pretty sure that this is supposed to be picked up based on the user and not simply running a "find me a GM user" for anyone.
If I understand your question correctly, shouldn't there be somewhere in betwen the start and end of this snipped that uses the login information to verify what level a user is it?
if((isset($_SESSION['login']) && $_SESSION['login'] ==true))
{
echo "";
// Shouldn't you run a query here to see who your user is?
// For example to get their ID?
}
else
{
header("location:login.html");
}
$mysql_hostname = 'localhost';
$mysql_usrnm = 'root';
$mysql_pass = '';
$mysql_db = 'user_info';
$con = mysqli_connect($mysql_hostname, $mysql_usrnm, $mysql_pass, $mysql_db) or die('Cant connect to database');
mysqli_select_db($con,$mysql_db);
$result = mysqli_query($con, "SELECT desig FROM members WHERE desig='gm'");
// Then here, instead of running this, convert it to something similar to:
$result = mysqli_query($con, "SELECT desig FROM members WHERE userid=$id");
Edit:
Storing the variable is easy - but you have to GET it from somewhere.
You can do this by popping a column in your users table - where you verify the username and password to begin with. I would suggest you look into a basic table like this to store user information. (I would also recommend you store hashes of passwords and the like, but that seems a conversation for another time).
user table:
userID username password userLevel
1 someUser somePass Grunt
2 someUser1 somePass1 MGR
3 someUser2 somePass2 MGR
4 someUser3 somePass3 GM
Armed with this, you can fire off a quick query to the database, verify the username and password, and get their userLevel quite easily.
Once you have the level, you can store it in a session variable if you like and have your code apply logic depending on what is stored in there.
I fixed the problem. There were some logical errors in my code.
if((isset($_SESSION['login']) && $_SESSION['login'] ==true)) {
//Selecting the whole row to compare and display different variables
$sql = "SELECT * FROM members WHERE username = '".$_SESSION['username']."'";
if(!$sql)
echo mysql_error();
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
//Using $row variable to fetch and compare the value stored in 'desig' with 'gm'
if($row["desig"]=='gm')
header("location:gm.php"); //Opens up different page for gm aka Gen. Mgr.
}
else
header("location:login.html"); //Redirects to this page if no user is logged in.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
The coding below works like when a user clicks submit, he get one ticket (lodd) and loses five points because he bought one ticket for five points. But I miss when a user don't get five points he can't buy. I want that if the user doesn't get enough points then an echo says (example):
Sorry, but you need at least five points to buy a ticket.
How can I do that? Now people only go in minus if they buy more than they have.
<?php
session_start();
//=============Configuring Server and Database=======
$host = 'localhost';
$user = 'root';
$password = '';
//=============Data Base Information=================
$database = 'login';
$conn = mysql_connect($host,$user,$password) or die('Server Information is not Correct'); //Establish connection with the server
mysql_select_db($database,$conn) or die('Database Information is not correct');
//===============End Server Configuration============
//=============Starting Registration Script==========
$username = mysql_real_escape_string($_POST['txtusername']);
//=============To Encrypt Password===================
//============New Variable of Password is Now with an Encrypted Value========
$insert = "UPDATE `users` SET `points` = (`points`-5) WHERE `username` = '".$username."'";
mysql_query($insert);
// Other code
$insert = "UPDATE `users` SET `lodd` = (`lodd` +1) WHERE `username` = '".$username."'";
mysql_query($insert);
mysql_query($insert);
header('location: succes.php');
?>
This is the code that give people one ticket for five points:
$insert = "UPDATE `users` SET `points` = (`points`-5) WHERE `username` = '".$username."'";
mysql_query($insert);
// Other code
$insert = "UPDATE `users` SET `lodd` = (`lodd` +1) WHERE `username` = '".$username."'";
mysql_query($insert);
mysql_query($insert);
First, mysql_* are deprecated so you should look at changing them at some point. One option is to use: MySQLi
Back to your question, you could do this:
$insert = "UPDATE `users` SET `points` = (`points`-5) WHERE `username` = '".$username."' and points > 5";
mysql_query($insert);
if (mysql_affected_rows() > 0)
{
// other codes
$insert = "UPDATE `users` SET `lodd` = (`lodd` +1) WHERE `username` = '".$username."'";
mysql_query($insert);
}else{
echo "You don't have enough points";
}
I have just found a pretty major vulnerability in my code while doing some testing,
Basically if my username was "admin" and password was say "12345"...
and a user joined with and chose the name "Admin" and the same password "12345"
when he/she goes to login they will be in my account on the website, As you can imagine I have created quite a flaw, as this would affect every potential user on the site.
So, my question is what can I change in this statement to make it check for an EXACT match.
WHERE login_name ='$user' AND user_password ='$pass' LIMIT 1";
Heres the login_process.php file
<?php
require_once("includes/session.php");
$connection = mysql_connect("localhost", "user", "password");
if(!$connection)
{
die("Database connection failed: " . mysql_error());
}
$db_select = mysql_select_db("game", $connection);
if(!$db_select)
{
die("Database selection failed: " . mysql_error());
}
$user = mysql_real_escape_string($_POST['username']);
$pass = mysql_real_escape_string($_POST['password']);
$pass = sha1($pass);
// Need to make a change to the below query, as it doesn't match for case sensitivity.
$query = "SELECT user_id, user_name, user_level FROM users WHERE login_name ='$user' AND user_password ='$pass' LIMIT 1";
$result=mysql_query($query);
if(mysql_num_rows($result) == 1)
{
$found_user = mysql_fetch_array($result);
$_SESSION['user_id'] = $found_user['user_id'];
$_SESSION['user_name'] = $found_user['user_name'];
$_SESSION['user_level'] = $found_user['user_level'];
header("Location: index.php");
}
else
{
echo "The username or password you entered was incorrect. <br/> Please click <a href='login.php'>Here</a> to try again.";
}
?>
the default collation of database is case insensitive . so the user admin and Admin or adMin are the same. While creating user check the database whether same username already exist or not.
it seems that you are using case sensitive collation.. you can use case insensitive collation for that user table so that your query will work fine.
or
while creating user and checking the database for duplicate entry use LCASE function as follows
SELECT * FROM USERS WHERE LCASE(username) = 'admin'
You should have a UNIQUE constraint on your login_name column:
alter table users add constraint unique (login_name)
That should take care of any new entries that are added that only differ from existing entries by case (assuming of course that you're using the default case insensitive collations). If you get complaints like
ERROR 1062 (23000): Duplicate entry 'XXX' for key 'login_name'
then you already have duplicates and you'll need to clean those up before adding your UNIQUE constraint.