Bit confused with this one.
Basically, I have a column in a table, and I want to retrieve the value in that column, for a specific row.
I have one set of code that works, but not in this particular situation.
The code I have that works is this:
$qry="SELECT * FROM logins WHERE username='$login' AND password='$password'";
$result=mysql_query($qry);
This obviously retrieves that particular row, and then:
$member = mysql_fetch_assoc($result);
$_SESSION['SESS_MEMBER_ID'] = $member['User ID'];
This successfully sets the session variable, as the value from the user id column from this row.
So that's fine, that works. The code I am trying to use in my new situation is this:
$qry = "SELECT * FROM vote WHERE Username = '" .$_SESSION['SESS_USERNAME']. "'";
$result = mysql_query($qry);
This gets the row based on the current user, and then:
while($row = mysql_fetch_array( $result ))
{
Print "<b>Name:</b> ".$row['Username'] . " <br>";
Print "<b>Vote:</b> ".$row['Vote'] . " ";
}
The while loop works correctly, it displays the current username, and their vote. Obviously I felt the loop was not required as I already have just the one row selected. Removing the loop broke it, so I put it back. Not a big deal, I can live with that if it gets the job done.
The issue I am focusing on, is the use of the
$row['Username']
In this if statement:
if($row['Username'] == "Admin") {
echo ("Win!<br />");
}
else {
echo "Failed!";
}
When printing from the loop above, it prints:
Name, as Admin,
and vote, as 0.
If I then try to validate using the if statement, I ask it to echo Win! if the username == Admin.
Obviously it is true as it has printed it on the line before, however, it always prins Fail! and I can't understand why.
Should I set $row['Username'] as some other variable?
Can anyone offer their guidance please?
Cheers
Eds
The problem stems from your loop:
while($row = mysql_fetch_array( $result ))
{
Print "<b>Name:</b> ".$row['Username'] . " <br>";
Print "<b>Vote:</b> ".$row['Vote'] . " ";
}
The first time through, $row
is set to the row of data from the database. It then tries to go through the loop again, but since there is only one row, mysql_fetch_array
returns false
. now $row
is set to false
. So any code after the loop won't have access to the data anymore.
The solution would be to replace your loop with a simple if statement:
if ($row = mysql_fetch_array( $result ))
{
Print "<b>Name:</b> ".$row['Username'] . " <br>";
Print "<b>Vote:</b> ".$row['Vote'] . " ";
}
I fail to see how your PHP code could produce that "it prints" sample. However, check that your Username
field actually contains an exact "Admin" string. It may have a linebreak or other whitespace in it. Doing a
var_dump($row['Username']);
should show something like
string(5) Admin
The bracketed number (5) is the length of the string. If it's not 5, then you've got some extra stuff in the string causing the == 'Admin'
test to fail.