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
    `mysql_query()` returns a statement handle, not the field(s) you selected. You need to `fetch` a row first: http://php.net/mysql_fetch_assoc and note that the mysql_*() functions are deprecated/obsolete, and you should NOT be using them anymore. – Marc B Jul 02 '14 at 18:32

2 Answers2

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.

Community
  • 1
  • 1
John Conde
  • 217,595
  • 99
  • 455
  • 496
1

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

$user=mysql_fetch_array($userArray);

If(!empty($user)){

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

}

nosdalg
  • 571
  • 1
  • 5
  • 23