0

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!

4 Answers 4

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Try doing this:

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

and

var_dump($row['UserId']);

and paste the output here.

Comments

0

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.

Comments

0

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!

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.