开发者

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

I have written the 开发者_如何学Ccode 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;
        ?>


try

echo $row2[0];

or even

print_r($row2); 

to see what you are getting from db.


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.


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


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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜