tags:

views:

44

answers:

4

Hi, I have this weird problem where PHP5 is not retrieving ints from a MySql database. This is the code I have:

$db = mysql_connect('XX.XX.XX.XX', 'DBName', 'DBPwd');
$query = 'Select * FROM Users WHERE UserName = \'Carlo\'';
$result = mysql_query($query);

if(!$result)
{
   echo 'Could not successfuly run query: '.mysql_error();
   exit;
} 

if(mysql_num_rows($result) == 0)
{
   echo '0 results';
}

$row = mysql_fetch_assoc($result);

echo 'UserId: '.$row['UserId']; // THIS IS THE INT VALUE FROM THE DATABASE

echo 'UserName: '.$row['UserName']; // THIS IS A STRING VALUE FROM THE DATABASE

mysql_close($db);

The code prints:

UserId:

UserName: Carlo

Any suggestion is greatly appreciated!

+1  A: 

Take a look at the array - you've probably got a typo or mis-capitalised word in there somewhere:

print_r($row);

This will show you all the keys and values.

nickf
+1  A: 

Try doing this:

var_dump(array_key_exists('UserId', $row));

and

var_dump($row['UserId']);

and paste the output here.

Alix Axel
A: 

You're connection string is wrong and you also need a select db command:

$db = mysql_connect('XX.XX.XX.XX', 'user', 'DBPwd');
if ($db === false) {
    trigger_error('Failed to connect to database', E_USER_ERROR);
    echo 'Unable to connect to database. Please come again later.';
    exit;
}

if (!mysql_select_db('db_name', $db)) {
    trigger_error('Failed to selected database', E_USER_ERROR);
    echo 'Unable to connect to database. Please come again later.';
    exit;
}

Also, check to ensure you table as the column UserId.

Darryl Hein
A: 

Perfect! That worked, I did have a mis-capitalized word, it was UserID instead of UserId. I usually name my ID fields in the databases as "SomethingId" that's the reason I didn't even though of that!

Thanks a lot!

Then you'll need to accept someones answer and post your response there instead, instead of answering your own question.
Darryl Hein