John
John

Reputation: 27

Why does this simple mysql_query/SELECT/echo get "Array" as output?

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;
        ?>

Upvotes: 0

Views: 251

Answers (6)

bfavaretto
bfavaretto

Reputation: 71918

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.

Upvotes: 0

dotancohen
dotancohen

Reputation: 31481

$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).

Upvotes: 0

Jonathan M
Jonathan M

Reputation: 17451

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

Upvotes: 0

Kęstutis
Kęstutis

Reputation: 545

try

echo $row2[0];

or even

print_r($row2); 

to see what you are getting from db.

Upvotes: 2

cdhowie
cdhowie

Reputation: 169018

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.

Upvotes: 1

yoda
yoda

Reputation: 10981

<?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'];
?>

Upvotes: 0

Related Questions