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;
        ?>
John
  • 27
  • 5
  • Please also add a [mysql] tag to your question. I was going to do that, but somehow the retag link is missing. – bfavaretto Sep 09 '11 at 21:55
  • 1
    And while you're at it, read: [Best way to stop SQL Injection in PHP](http://stackoverflow.com/questions/60174/best-way-to-stop-sql-injection-in-php) –  Sep 09 '11 at 22:18

6 Answers6

2

try

echo $row2[0];

or even

print_r($row2); 

to see what you are getting from db.

Kęstutis
  • 535
  • 7
  • 18
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.

cdhowie
  • 158,093
  • 24
  • 286
  • 300
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'];
?>
yoda
  • 10,834
  • 19
  • 64
  • 92
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

Jonathan M
  • 17,145
  • 9
  • 58
  • 91
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).

dotancohen
  • 30,064
  • 36
  • 138
  • 197
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.

bfavaretto
  • 71,580
  • 16
  • 111
  • 150