user2996892
user2996892

Reputation: 33

Cannot access user's first name after simple MYSQL query

I would like to have "Welcome, [user's name]!" appear on a page of my website.

I perform this query:

Option 1 I tried:

$first_name = mysql_query("SELECT first_name FROM users WHERE id = $user_id");

echo "Welcome, " . $first_name . "!";

Option 2 I tried:

$users = mysql_query("SELECT * FROM users WHERE id = $user_id");

    if (count($user) == 1)
    {
        // first (and only) row -- meaning only one user in this array
        $user = $users[0];

        echo "first_name: " . $user['first_name'] . "!";
    }

A row in my users table looks like this: id | first_name | last_name | email | password

I have tested and I successfully have the user's id. My SQL query is also tested and works.

This is php code inserted into HTML code.

I'm struggling in accessing the first_name of the user -- any help is appreciated!

Upvotes: 0

Views: 71

Answers (2)

John Conde
John Conde

Reputation: 219824

You forgot to fetch your results

$users = mysql_query("SELECT first_name  FROM users WHERE id = $user_id");
$row = mysql_fetch_assoc($users);
echo $row['first_name'];

FYI, you shouldn't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

Upvotes: 2

nosdalg
nosdalg

Reputation: 571

$userArray= mysql_query("SELECT * FROM users WHERE id = $user_id");

$user=mysql_fetch_array($userArray);

If(!empty($user)){

        echo "Welcome, " . $user['first_name']. "!";

}

Upvotes: 1

Related Questions