Reputation:
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!
Upvotes: 0
Views: 87
Reputation:
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!
Upvotes: 0
Reputation: 145127
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
.
Upvotes: 0
Reputation: 154681
Try doing this:
var_dump(array_key_exists('UserId', $row));
and
var_dump($row['UserId']);
and paste the output here.
Upvotes: 1
Reputation: 546503
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.
Upvotes: 1