0

I have written the code below, which should check the session variable against the database and give me the username which = user id which is in the session.

If I echo $session_name; I get a user id e.g. 30 If I echo $row2; I get Array

What am I doing wrong?

<?php
        connect();
        $session_name = $_SESSION[id];
        $sql2 = "SELECT username FROM members WHERE member_id = '$session_name'";
            $result2=mysql_query($sql2);
            $row2 = mysql_fetch_array($result2);
        echo $row2;
        ?>
2
  • Please also add a [mysql] tag to your question. I was going to do that, but somehow the retag link is missing. Commented Sep 9, 2011 at 21:55
  • 1
    And while you're at it, read: Best way to stop SQL Injection in PHP Commented Sep 9, 2011 at 22:18

6 Answers 6

2

try

echo $row2[0];

or even

print_r($row2); 

to see what you are getting from db.

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

Comments

1

Try echoing $row2[0]. mysql_fetch_array returns one result row as an indexed array, which in this case has only one element/column. Also don't forget to test if $row2 === FALSE, which indicates that there were no results for the query.

Comments

0
<?php
        connect();
        $session_name = $_SESSION[id];
        $sql2 = "SELECT username FROM members WHERE member_id = '$session_name' LIMIT 1";
            $result2=mysql_query($sql2);
            while($row2 = mysql_fetch_assoc($result2))
               echo $row2['username'];
?>

1 Comment

perfect exactly what i wanted. Works perfectly
0

The result of a fetch is always an array. In this case it's a one-dimensional array. Use $row2[0] (assuming your fetchmode is an array).

If your fetchmode is associative or object, it'd be $row2['username'].

Check here for more good info: http://php.net/manual/en/function.mysql-fetch-array.php

Comments

0

$row2 is in fact an array that represents the entire row returned. Try $row2[0], I think that will give you what you expected (the single field in the returned row).

Comments

0

That's because $row2 is an array. You used mysql_fetch_array to obtain it, and it returns an array, as the name of the function implies.

The array returned by mysql_fetch_array uses the column names from your SQL query as the keys. Thus

echo $row2['username'];

will return the data you expect.

As a sidenote: SELECT is technically a SQL clause, not a PHP function.

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.