franglais
franglais

Reputation: 938

PHP MSSQL variable not working?

Very confused and have probably overlooked something, but some ideas would be appreciated!

I have a query as follows:

$usernamequery = "select username + ' ' + surname as username, userid from users where username + ' ' + surname = '$username'";
$usernamestmt = sqlsrv_query( $conn, $usernamequery);
if( $usernamestmt === false ) {
 die( print_r( sqlsrv_errors(), true));
}

while( $obj = sqlsrv_fetch_object( $usernamestmt)) 
{
echo    $username1 = $obj->username;
echo    $userid = $obj->userid;
}

which doesn't return anything, however when I echo out the $usernamequery I get

select username + ' ' + surname as username, userid from users where username + ' ' + surname = 'Joe Bloggs' 

When I then go and run that directly in SQL it returns the results I'm expecting.

What's more odd is that when I then change the PHP to the actual query (i.e.

select username + ' ' + surname as username, userid from users where username + ' ' + surname = 'Joe Bloggs' 

)

it runs like a charm and returns the results I'm expecting.

All in all, I'm dead confused...!

Upvotes: 0

Views: 462

Answers (2)

Álvaro González
Álvaro González

Reputation: 146660

My educated guess is that $username does not contain what you think it does. It possibly has a tabulator or more than one spaces, but you're possibly echoing it into HTML and the browser is collapsing blank space into a single space.

You can inspect the exact contents of a variable with var_dump(), e.g.:

var_dump($username);

... of, if you need further details, with bin2hex();

var_dump(bin2hex($username));

Upvotes: 1

Sudar
Sudar

Reputation: 20030

Change the query to

$usernamequery = "select username + ' ' + surname as fullname, userid from users where fullname = '$username'";

Upvotes: 0

Related Questions