Nilesh
Nilesh

Reputation: 281

PHP-showing weird entries when retrieved from database

I have written this PHP code but it is giving some weird result. The snippet is

$queryIsbnArr = mysql_query("select ISBN from quotation_master") or die(mysql_error());
            $row = mysql_fetch_array($queryIsbnArr) or die(mysql_error()); 
            print_r($row);
            $_SESSION['isbnArr'] = $row;

The output which the query is giving is..

Array ( [0] => 12121 [ISBN] => 12121 ) 

Where as the output which is query is giving when run on the database is

12121
56

Which is correct.What is the problem with this then?

Upvotes: 1

Views: 34

Answers (2)

John Conde
John Conde

Reputation: 219824

Read the manual!

Returns an array of strings that corresponds to the fetched row, or FALSE if there are no more rows. The type of returned array depends on how result_type is defined. By using MYSQL_BOTH (default), you'll get an array with both associative and number indices.

mysql_fetch_array() fetches both a numerical and associative array of each row's data. You need to use or the other to get the actual data as $row contains the entire dataset as an array even if it is only one value.

$queryIsbnArr = mysql_query("select ISBN from quotation_master") or die(mysql_error());
$row = mysql_fetch_assoc($queryIsbnArr) or die(mysql_error()); 
print_r($row['ISBN']);
$_SESSION['isbnArr'] = $row;

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.

Upvotes: 2

kamal pal
kamal pal

Reputation: 4207

It's perfectly fine, when you use mysql_fetch_array it will get you value in both places, by index and column name

and for multiple rows you have to loop through like:-

while($row = mysql_fetch_array($queryIsbnArr)){
    print_r($row);
}

Upvotes: 0

Related Questions