I have been programming for a while but pretty new to PHP. I am have run into a problem. My site has a login/register screen and once logged into the account, I am trying to echo information from the users database entry. For example if I want to display the content "Balance" I have been trying the following code:
<?php
$data = mysql_query("SELECT * FROM users WHERE username=username") or die(mysql_error());
while($info = mysql_fetch_array( $data ))
{
Print $info['balance'];
}
?>
The idea is that the script will query the database using the username stored in the session then goto the named field.
When there is only one registered user, it appears to work, however; once multiple users enroll, it echoes the value from ALL users (ex. $7.50$10.12).
Thanks for your help in resolving this issue!
Currently you are not comparing the username to a variable, but you are comparing it to itself, which means it will always be true.
<?
$username = $_SESSION['username'];//or other methods like $_POST['username'] or $_GET['username'], depending on how you intend to get the username;
$data = mysql_query("SELECT * FROM users WHERE username='$username'") or die(mysql_error());
while($info = mysql_fetch_array( $data ))
{ Print $info['balance']; }
?>
You neet to make sure the $username is escaped (if comes from user input) as well as start using mysqli or pdo instead of mysql.
And, of course, I'm assuming you are using session_start() somewhere and actually assigning the username to the session.
Hope this helps!
Related
This is the code for my log in forum. The problem with it is that it only accepts as correct credentials the first username and password (basically only the first row) any ideas as to how i could change it ?!
<?php
session_start();
include_once("connect.php");
$token = "";
if($con->connect_error){
die("Connection failed: ".$con->connect_error);
}
$sql = "SELECT * FROM authme";
$result = mysqli_query($con, $sql) or die(mysqli_error($con));
while(mysqli_num_rows($result)>0){
while($row = $result->fetch_assoc()){
if(isset($_POST['realname']))
$username = $_POST['realname'];
if($result->num_rows>1){
if(mysqli_num_rows($result)>1){
$_SESSION['uid'] = $row['id'];
$_SESSION['realname'] = $row['realname'];
}
$password = '$SHA$'.substr($row['password'],5,16).'$'.hash('sha256', hash('sha256',$_POST['password']).substr($row['password'],5,16));
if($password == $row['password'] ){
header("Location: index.php");
exit();
}
else {
echo "INVALID INFORMATION, PLEASE RETURN!";
// header("location: index.php");
session_destroy();
exit();
}
}
}
}
?>
?
I decided to try to make a log in forum that uses a database which encrypts the passwords it receives through a register form. This code only takes as correct the first username and password i give in and its not enough, as you could imagine.
Welcome to programming with PHP. I'm going to try to share a few principles that may help you solve your problem.
1.) One of the best features in PHP is the print_r() function. Using this function you can output almost anything to text in the browser. So in this case you may want to insert a print_r($result) immediately following this line "$result = mysqli_query($con, $sql) or die(mysqli_error($con));". This will output the results of the query that PHP is receiving. This can be used to help you troubleshoot and determine why your code isn't working. Once you're done troubleshooting delete that line.
2.) You seem to have multiple checks for the number of rows inside the while loop. I'm not sure why you have thoose there, but you may want to check if those are causing your trouble by using echo or print to display to values in the browser for troubleshooting. Once you're done troubleshooting delete that line.
3.) Another overall concept for the data you are querying. It is inefficient to send a query that gets the entire table and returns it to the program, that then loops through every row looking for the data. Instead you should write an SQL query to return only the row of data the you want. Make sure you do use prepared statements.
4.) Your coding standards could use some improvement, if you clearly tabbed your statements it would be easier to read. Consider reading PSR-2. For example this code seems to be missing {}'s.
if(isset($_POST['realname']))
$username = $_POST['realname'];
The application is a chat application with login verification. It implements Ajax, PHP, MySQL, and HTML. Everything works except that when two users are logged in under different names, after they type the first message and the page refreshes both their browsers synchronize as if they are the same user. They end up having a conversation with themselves. I need both user to be able to update the database with their message separately as individual users and have the application distinguish between the two users.
This is the query that updates the message column of the database of the user sending the message:
$query = "UPDATE chatLogs SET msg = '$msg' WHERE userName='$uName'";
This is how I am grabbing the user info and the buddy in the database that they wish to speak to:
<?php
$uName = $_POST["userName"];
$pwd = $_POST["pwd"];
$buddy = $_POST["chatBuddy"];
$result = $link->query($query);
if(!$row=$result->fetch_assoc()){
header("Location: chat.php");
}
else{
$_SESSION['userName'] = $uName;
$_SESSION['chatBuddy'] = $buddy;
header("Location: chatBox.php");
}
?>
Okay so this problem is really boggeling my mind... I have a MYSQL query I want to make so that my php program can access and update the database with lat and long coordinates of a user and im getting issues...
This is non working code:
$currUsername = strtolower($_SESSION['username']);
$sql= "UPDATE users SET pos_Lat=$latitude, pos_Long=$longitude WHERE username=$currUsername";
$result = mysql_query($sql, $link);
The working code
$currUsername = "email_that_is_returned"
$sql= "UPDATE users SET pos_Lat=$latitude, pos_Long=$longitude WHERE username=$currUsername";
$result = mysql_query($sql, $link);
Is this because session returns data that is not able to be placed inside a query?
Check whether the session was started or not. if not started then add the following code to your page and then check its working or not.. i thing your session does not return any value.. so start session by using the code session_start();
session_start();
$currUsername = strtolower($_SESSION['username']);
$sql= "UPDATE users SET pos_Lat=$latitude, pos_Long=$longitude WHERE username=$currUsername";
$result = mysql_query($sql, $link);
You can check what type of data it is returning.
print $_SESSION['username'].
Also there is a chance to break the SQL query if the $_SESSION['username'] returns data with spaces. Make sure the SQL query not failing even if the $_SESSION['username'] contains spaces and singlequotes etc..
Okay, I can post the PHP code if needed but I'm trying to use some data in my database, but have no idea how I can access it. It might be an easy reply but I'm new to this game...
Basically, I have been able to set up a login system for my site, where if you log in, it will display the logged in user's username, this is done through the use of $_SESSION and a session class.
Where if the user is logged in ($session->logged_in) etc
<h3>Welcome <? echo $session->username?> </h3>
</head>
<body>
<p> Welcome to the website, your details are below </p>
</body>
<?php } ?>
I return the user's username as such.
However, I can only currently access data from the table 'users', and 'users' is connected through foreign keys to a table called 'passengers' through the 'username' field.
What I would like to do, is instead of printing the username, print the user's surname.
So essentially it is like:-
Logging in sets up a session and recognises the username that is logged in.
By querying this username in a different table, can pull up data from all corresponding tables in the database.
But I have no idea how to go about it..
If you guys and girls know of any sample code, or could point me in the right direction that'd be fantastic.
<? php
mysql_connect("localhost", "username", "password");
mysql_select_db("databasename");
$query = "SELECT surname FROM passengers WHERE username = " . $session->username . "";
$result = mysql_query($query);
$data = mysql_fetch_assoc($result);
echo "Hello, your lastname is $data";
?>
I think this is what you are referring to?
Also, even though you're new at php etc., try looking into mysql injection and how to prevent it (this current code is very susceptible to mysql injection -- if it were to use user input; thanks to Carrie Kendall lol =])
Good place to start is by using mysql_real_escape_string.
edit-
Not sure but this might also help out as I'm not entirely sure what you mean; mysql (left) join
EDITThanks to the comments below it has been figured out that the problem lies with the md5, without everything works as it should.
But how do i implent the md5 then?
I am having some troubles with the following code below to login.
The database and register system are already working.
The problem lies that it does not find any result at all in the query.
IF the count is > 0 it should redirect the user to a secured page.
But this only works if i write count >= 0, but this should be > 0 , only if the user name and password is found he should be directed to the secure (startpage) of the site after login.
For example root (username) root (password) already exists but i cannot seem to properly login with it.
<?php
session_start();
if (!empty($_POST["send"]))
{
$username = ($_POST["username"]);
$password = (md5($_POST["password"]));
$count = 0;
$con = mysql_connect("localhost" , "root", "");
mysql_select_db("testdb", $con);
$result = mysql_query("SELECT name, password FROM user WHERE name = '".$username."' AND password = '".$password."' ")
or die("Error select statement");
$count = mysql_num_rows($result);
if($count > 0) // always goes the to else, only works with >=0 but then the data is not found in the database, hence incorrect
{
$row = mysql_fetch_array($result);
$_SESSION["username"] = $row["name"];
header("Location: StartPage.php");
}
else
{
echo "Wrong login data, please try again";
}
mysql_close($con);
}
?>
The best thing you can do in such situations is trying to find out where the problem lies.
So, you could proceed by steps and do the following:
1) start your script with a print_r($_POST), to see what variables are passed by post (by absurd, the problem might even be related to the 'send' guard parameter you have ..IE a form being sent through get)
2) Assign your query to a variable (...and don't forget to escape parameters!) and print it to screen; and then exec it on mysql (or phpmyadmin) to see what results they give.
As a side note, as someone already pointed out, this code might be subject to SQL-injection, so you might consider using prepared statements; see here: quick intro
Your login code is good.
But you also need to use md5() function BEFORE storing the password in the database. So when you are inserting the user record in the DB , apply the md5() to the password , save in the DB. Now when you will try to find the record on login, it will match correctly.
You should rewrite this with mysqli or PDO and using a newer hash function as well as a salt. MD5 is very widely used and is a target for crackers.