Hyperion
Hyperion

Reputation: 2625

Cannot print database value using PHP

I've got a datbase with a simple table called "channels" which has 2 fields: id and link. I use this code in my php page to get the link of the channel with id 1:

<!DOCTYPE html>
<html>
<body>

<?php
$db = mysql_connect("localhost", "username", "");
mysql_select_db("my_database", $db);
$result = mysql_query("SELECT link FROM channels WHERE id='1'");
$data = mysql_fetch_array($result);

print $data;
?>
</body>
</html>

but what I get as output is a page with the text "Array" and anything else. id field is an INT value and link is TEXT. How can get my data correctly and print it?

Upvotes: 1

Views: 66

Answers (3)

Martin Ibert
Martin Ibert

Reputation: 1

What you get back from mysql_fetch_array($result) is an array that represents one row from the result set. It is an array because you could have many columns on your result row, not just one as in your example.

Try printing

$data['link']

instead.

Some posters have suggested looping over the result as a SELECT statement can return more than one row. Good idea in principle but misleading here. mysql_fetch_array() gets only one result row at a time (it is an array, indexed by column name). If you are expecting more than one result, call mysql_fetch_array() repeatedly until the result is empty (mysql_num_rows($result) is 0).

Just seeing another issue. You say that the id column is an integer value. In that case you need to compare it to an integer literal, not to a string/varchar/text literal:

SELECT link FROM channels WHERE id = 1

Upvotes: 0

I. Bielderman
I. Bielderman

Reputation: 43

You should create a while loop

while ($data = mysql_fetch_array($result)) {
    print $data['link'];
}

Looking at your query you probably only expect one result, you could just do print $data['link'];

Upvotes: 0

cjds
cjds

Reputation: 8426

Apart from the insecurity stuff (probably look at mysqli and PDO) this is how you access data

<?php 
$db = mysql_connect("localhost", "username", "");
mysql_select_db("my_database", $db);
$result = mysql_query("SELECT link FROM chhannels WHERE id='1'");
$data = mysql_fetch_array($result);

print $data["link"]; //access the first column of the first row (in this case link)
?>

This only returns the first row. To get all the rows, you have to call mysql_query repeatedly

while ($row = mysql_fetch_array($result)) {
    print $row["link"];
}

Upvotes: 1

Related Questions