0

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!

1
  • 1
    mysql_query() returns a statement handle, not the field(s) you selected. You need to fetch a row first: php.net/mysql_fetch_assoc and note that the mysql_*() functions are deprecated/obsolete, and you should NOT be using them anymore. Commented Jul 2, 2014 at 18:32

2 Answers 2

2

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.

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

3 Comments

Hm, tried using this but no luck...any other suggestions?
You'll need to do better when describing why this doesn't work. We can't guess what code you have. The code above is functional so if it doesn't work you're implementing it incorrectly.
Thanks, I must not be connecting to my database correctly. I'll work on it.
1

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

$user=mysql_fetch_array($userArray);

If(!empty($user)){

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

}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.