mysql - fetching data from table row - php

I have gotten a snippet of code to bring back the username and password and see if they match. i now want to set a session varaible to the 'points' value i have in the table which is in the same row as the username and pass.. what could be done?
<?php $username="asdin";
$password="1sdA2";
$database="a75sdting";
$pword = $_REQUEST['pword'];
$uname = $_REQUEST['uname'];
mysql_connect('mysqsdst.com',$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
$query = mysql_query("SELECT * FROM `username` WHERE `password` = '$pword' AND `username` = '$uname'");
$exsists = 0;
WHILE($rows = mysql_fetch_array($query)){
$exsists = 1;
break;
}
if ($exsists){
$_SESSION['usern']=$uname;
$_SESSION['logged']=1;
header('Location: http://wwsdipts/logged2.php');
}
mysql_close();
?>
i want to set $_SESSION['points'] = $row[points] i guess... but i dont think that is correct

<?php
// start session (required on every page that uses sessions
session_start();
// db auth
$username="asdin";
$password="1sdA2";
$database="a75sdting";
// user auth
$pword = $_POST['pword']; // should use either $_POST or $_GET, NOT $_REQUEST
$uname = $_POST['uname']; // should use either $_POST or $_GET, NOT $_REQUEST
// open db connection
$conn = mysql_connect('mysqsdst.com',$username,$password);
#mysql_select_db($database,$conn) or die( "Unable to select database");
// check user
$query = mysql_query("SELECT * FROM `username` WHERE `password` = '$pword' AND `username` = '$uname'");
if(mysql_num_rows($query)){
// user exists
$row = mysql_fetch_assoc($query);
$_SESSION['usern']=$uname;
$_SESSION['logged']=1;
header('Location: http://wwsdipts/logged2.php');
}else{
header('Location: http://wwsdipts/login.php'); // take them back to login page if incorrect details
}
// close db connection
mysql_close($conn);
?>
I've tidied up your code a bit, please take a look at the notes. It is also worth nothing the following:
You should be using some sort of protection against SQL injections, such as mysql_real_escape_string($_POST['uname']) - the same for password
You need session_start() on all pages that use session variables
You shouldn't use $_REQUEST, use either $_POST or $_GET (read about it)
Do you actually have a table named username? You should read up a bit about DB design, a better name/use for this table would be users as the table will be holding users (a combination of unique ID, username & password.
I don't know what you mean about points, but to access any column name in the "username" table, use $row['column-name'] after it is set ($row = mysql_fetch_assoc($query);)
If you intend on using PHP a lot in the future, you should look up PDO, it's a great class for handling SQL.

you are right, but in this case your array is rows, and it should be in
$_SESSION['points'] = $rows['points']
And it should be in your while loop:
WHILE($rows = mysql_fetch_array($query)){
$exsists = 1;
$_SESSION['points'] = $rows['points']
break;
}
However, it might be better to do something like this:
if(mysql_num_rows($result) == 1) {
//Login Successful
rows = mysql_fetch_assoc($result);
$_SESSION['points'] = $rows['points']
$_SESSION['usern']=$uname;
$_SESSION['logged']=1;
header('Location: http://wwsdipts/logged2.php');
}

Related

page will not die() if the person is banned php mysql

<?php
include('session.php');
?>
<?php
require_once('mysql_connect.php');
$query2 ="SELECT id, username, banned FROM login WHERE username ='$login_session'";
$result2 = mysql_query($query2) OR die($mysql_error());
$row = mysql_num_rows($result2);
if($row['banned'] == 1) {
die();
}
?>
Session.php
<?php
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect("localhost", "", "");
// Selecting Database
$db = mysql_select_db("", $connection);
session_start();// Starting Session
// Storing Session
$user_check=$_SESSION['login_user'];
// SQL Query To Fetch Complete Information Of User
$ses_sql=mysql_query("select username from login where username='$user_check'", $connection);
$row = mysql_fetch_assoc($ses_sql);
$login_session =$row['username'];
if(!isset($login_session)){
mysql_close($connection); // Closing Connection
header('Location: login.php'); // Redirecting To Home Page
}
?>
As you can see , im trying to stop people who are banned from loading profile.php
it doesnt stop the profile page from loading
thanks fred, that worked – KIXEYE
make it to an answer, ill mark as answered as soon as i can – KIXEYE
As per the OP's wish:
You're using the wrong function for $row. Either use one that will fetch a row as an array, or change if($row['banned'] == 1) to if($row == 1) to work with mysql_num_rows.
Footnotes:
Your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements, they're much safer.
Example pulled from https://stackoverflow.com/a/6620252/
$user = "bob";
$user = mysql_real_escape_string($user);
$result = mysql_query("SELECT COUNT(*) AS num_rows FROM my_table WHERE username='{$user}' LIMIT 1;");
$row = mysql_fetch_array($result);
if($row["num_rows"] > 0){
//user exists
}
Edit:
If your banned row contains 1 or 0 to check if they're banned, then add another parameter to your where clause. I.e.: WHERE username ='$login_session' AND banned !=1 if banned column is an int type. If not, wrap 1 in quotes.
This translates to WHERE username exists and is 'John' and banned does NOT equal 1. Or make it 0, it's your choice.
Then why don't you just fetch user who are not banned:
$ses_sql = mysql_query("SELECT username FROM login WHERE username='$user_check' AND banned <> 1",$connection);
$numofresult = mysql_num_rows($ses_sql);
Then check if it has a result:
if($numofresult > 0){
/* SUCCESS */
}
else {
/* BANNED */
}
To compromise SQL injections, use mysql_real_escape_string() function.
$user = mysql_real_escape_string($username,$connection);
But a better recommendation is to use mysqli_* prepared statement or PDO.
if($stmt = $connection->prepare("SELECT username FROM login WHERE username='$user_check' AND banned <> 1")){
$stmt->execute();
$stmt->store_result();
$numofresult = $stmt->num_rows;
$stmt->close();
}
mysql_num_rows() returns a number of rows, not the rows themselves.
You should use mysql_fetch_assoc() or similar function.

assign $_session var from object

This is a login script I am working on; It uses mysqli (I know it is not as secure as PDO)
After running the MySQL query I am fetch_object(). I am then assinging $_session to hold the user ID and email. $_SESSION['uid'] = $user->ID works but not $_SESSION['uemail'] = $user->email. Could this be because of email is stored in the object $user? Do I have to convert it somehow?
email is store ass a varchar(255) in the database ID is a int(11).
<?php
include_once("config.php");
$username = $_POST['username'];
$password = sha1($_POST['password']);
$query = "SELECT ID FROM user WHERE username = '$username' AND password = '$password' LIMIT 1";
if ($result = $db->query($query)) {
while ($user = $result->fetch_object()) {
$_SESSION['uid'] = $user->ID;
$_SESSION['uemail'] = $user->email ;
header("Location: index.php");
//exit();
}
}else {
echo "Invalid login information. Please return to the previous page.";
//exit();
}
//var_dump(get_object_vars($result));
//$db->close();
?>
Thanks in advance.
Comment to answer:
You need to select the column(s) for which you are querying for:
SELECT ID, email FROM ...
which is why $_SESSION['uemail'] = $user->email ; is failing.
Either choose the specific column(s) in question, or a SELECT * would also work.
However and it's been said before, that using * isn't suggested, therefore select the actual column(s).
you are not selecting the email column from the database.
Try:
$query = "SELECT ID, email FROM user WHERE username = '$username' AND password = '$password' LIMIT 1";

Unable to fetch and compare mysql data in php

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.

user login with php and mysql database

I'm new to mysql and php.
Been working on creating a database with a table for users.
I've managed to successfully add users to the database, and their passwords with md5(yea i know it's not secure), it's not going to be launched online.
My problem is, how do I log a user in, based on their correct username and password.
here is my code
My logic is taht after the query runs, it will return either true or false.
If true, then display successful login, else unsuccessful.
however, even if i input a correct username and password, i still get a unsuccessful login message
i checked the mysql database, and the uesrname is in there correctly
ideas?
if(!empty($_POST['userLog']) && !empty($_POST['passLog']))
{
//set the username and password variables from the form
$username = $_POST['userLog'];
$password = $_POST['passLog'];
//create sql string to retrieve the string from the database table "users"
$sql = "SELECT * FROM `users` WHERE userName = '$username' AND password = md5('$password')";
$result = mysql_query($sql);
if ($result == true) {
$return = "<font color=#008000><Center><b>**Successful Login**</b></Center></font>";
} else {
$return = "<font color=#ff0000><Center><b>**Failed Login**</b></Center></font>";
}
print($return);
}
I'm not entirely sure your SQL will run, but just to be on the safe side.
Change it so that
$password_hash = md5($password);
$sql = "SELECT * FROM `users` WHERE userName = '$username' AND password = '$password_hash'";
And for your original question
if(mysql_num_rows($result) == 1) { //If the SQL returns one row, that means that a user was found with `userName = $username` and `password = md5($password)`
// Login
} else {
// Authentication Failed
}
Also, consider using MySQLi instead of MySQL since it has been depreciated.
First of all, protect your code against SQL injections.
Then, make sure that the password in the DB is really hashed with md5() function.
Make sure you form uses POST method to pass the data to the script.
Try the following code:
if(!empty($_POST['userLog']) && !empty($_POST['passLog']))
{
//set the username and password variables from the form
$username = $_POST['userLog'];
$password = $_POST['passLog'];
//create sql string to retrieve the string from the database table "users"
$sql = "SELECT * FROM `users` WHERE userName = '". addslashes($username) ."' AND password = '". md5('$password')."'";
$result = mysql_query($sql);
if (mysql_num_rows($result)>0) {
$return = "<font color=#008000><Center><b>**Successful Login**</b></Center></font>";
} else {
$return = "<font color=#ff0000><Center><b>**Failed Login**</b></Center></font>";
}
print($return);
}
mysql_query doesn't return TRUE or FALSE. Per the docs (http://php.net/manual/en/function.mysql-query.php), it returns a resource if successful, or FALSE if there is an error. You need to evaluate the resource to see if it's valid.
if(!empty($_POST['userLog']) && !empty($_POST['passLog']))
{
//set the username and password variables from the form
$username = $_POST['userLog'];
$password = $_POST['passLog'];
//create sql string to retrieve the string from the database table "users"
$sql = "SELECT * FROM `users` WHERE userName = '$username' AND password = md5('$password')";
$result = mysql_query($sql);
if ($result && $row = mysql_fetch_assoc($result)) {
$return = "<font color=#008000><Center><b>**Successful Login**</b></Center></font>";
} else {
$return = "<font color=#ff0000><Center><b>**Failed Login**</b></Center></font>";
}
print($return);
}
As mentioned in my comment, the issue seems to be your sql string. Instead of hashing, you are putting the method into the string. So change
$sql = "SELECT * FROM `users` WHERE userName = '$username' AND password = md5('$password')";
to
$sql = "SELECT * FROM `users` WHERE userName ='$username' AND password = '".md5('$password')."'";
Your result will not be true or false, but since php treats any value not a 0 as true, it will work as is.
Also, it is strongly recommended to escape all data going into your sql string to prevent sql injection. Another note: mysql is being deprecated, so now would be a great time to move to something like mysqli.

IF and ELSE statement not working

I am trying to award a user a badge if their points are 10,000. There is a field in the table called badge1 with a default value set to locked and a points row. I am running and if statement that if the users points are 10,000 then UPDATE the badge1 row from locked to unlocked. My code seems correct but It is neither updating the the field nor showing any errors.
<?php
$db = new PDO('mysql:host=hostname;dbname=databasename;charset=UTF-8', 'username', 'password');
$username = $_SESSION['username'];
$q = "SELECT Points FROM login_users WHERE username ='$username'");
$r = mysql_query($q);
$row = mysql_fetch_assoc($r);
$Points = $row['Points'];
if($Points == "10000") {
$awardBadge = $db->exec("UPDATE login_users SET badge1=unlocked WHERE username=?");
$Points->execute(array($username))
} else {
print "";
}
?>
UPDATE:
I managed to get it working.. however the problem is I am a bit new to converting old sql to PDO so this is not very secure but this is what works:
<?php
$connect = mysql_connect("host","username","password");
mysql_select_db("databasename");
$username = $_SESSION['jigowatt']['username'];
$q = "SELECT Points FROM login_users WHERE username = ('$username')";
$r = mysql_query($q);
$row = mysql_fetch_assoc($r);
$Points = $row['Points'];
?>
// Place somewhere
<?php
if($Points >= "10000") {
$result = mysql_query("UPDATE login_users SET maneki='unlocked' WHERE username='$username'");
} else {
print "Badge has not been unlocked";
}
?>
"10000" string should be an 10000 int
And also, you might want to make a choice here too. You're using 2 types of setting up a mysql-database connection. the old-fashioned mysql_function() way and the new fancy PDO method.
I think working with the PDO version is safer, since newer PHP versions will not support the old methods anymore... That... and it just looks dirty ;P
Try this:
<?php
session_start();
$dbSession = new PDO('mysql:host=***;dbname=***', '***', '***');
$selectQuery = $dbSession->prepare('
SELECT `User`.`Points`
FROM `login_users` AS `User`
WHERE `User`.`username` = :username
');
$selectQuery->bindParam(':username', $_SESSION['username'], PDO::PARAM_STR);
$user = $selectQuery->fetch(PDO::FETCH_ASSOC);
if ( !empty($user) && $user['Points'] == 10000 ) {
$updateQuery = $dbSession->prepare('
UPDATE `login_users`
SET `badge1` = \'unlocked\'
WHERE `username` = :username');
$updateQuery->bindParam(':username', $_SESSION['username'], PDO::PARAM_STR);
$updateQuery->execute();
}
?>
Usefull resources:
PHP Database Objects (PDO)
PHP Sessions
MySQL Datamanipulation
MySQL SELECT syntax
MySQL UPDATE syntax
Better check if >= 10000 and not yet awarded. That could you also be done in SQL so you don't need that logic in PHP.
UPDATE login_users SET badge1=unlocked WHERE points >= 10000 and badget1 <> unlocked
The issue is caused by $point value which actually is not equal to 10000, but is NULL.
So I propose to always use var_dump() to get the actual value of the variable in such cases.
one tip: check the PDO docs, before you write php code! You use PDO and mysql commands on same time for same job!?? why???
Try this if($Points == 10000) instead of if($Points == "10000")
mysql_query() sends a unique query (multiple queries are not supported) to the currently active database on the server that's associated with the specified link_identifier.
if($Points==10000){
$awardBadge = $db->prepare("UPDATE login_users SET badge1=unlocked WHERE username=?");
$awardBadge->execute(array($username));
}

Categories