Reputation: 1838
I'm getting this column in this bd
$result = mysql_query("SELECT short FROM textos");
and I'm trying to echo only one of the results based on the array it returns:
$col = mysql_fetch_assoc($result);
echo "<b>Short:</b>".$col[1]."<br/>";
apparently this $col array can't be accessed this way. How should it be done? Thanks
Upvotes: 0
Views: 576
Reputation: 1984
That has been already stated in comments above, so just a bit of explanation here.
mysql_fetch_assoc
retrieves a result row for you presented as an associative array (an array where keys are field names and values are field values). Your query returns only one field (which is short
), but still it doesn't make your row a single scalar value - it remains an array, only with a single element.
So you need to refer it as $row['short']
, or in your sample $col['short']
.
Bear in mind that query might return no results - you can learn that by checking if the returned value is not an array but scalar false
instead, e.g.
if ($col === false) {
echo 'Error occured<br/>';
} else {
echo "<b>Short:</b>".$col['short']."<br/>";
}
Putting LIMIT
into your query like again comments suggest is a good idea as well because you wouldn't be returning potentially huge amount of data when you only need one row actually. The result would still come as a multi-dimensional array though, so that part won't change.
Upvotes: 1
Reputation: 2136
There are three mysql_fetch functions which getting rows:
In your example you will get an array that is looking like this one for the function mysql_fetch_array():
array(2) {
[0]=>
string(3) "foo"
["short"]=>
string(3) "foo"
}
$statement = 'SELECT short FROM textos';
$result = mysql_result($statement);
if ($result) {
while ($row = mysql_fetch_assoc($result)) {
var_dump($row); // or echo "<b>Short:</b>".$row['short']."<br/>"; or something else you like to do with rows of the above statement
}
}
Upvotes: 1
Reputation: 11382
To access the first element use $col[0]['short']
.
If you only want to output one element anyways you can add LIMIT 1
to the MySQL query.
After querying you should check if the result array is set otherwise php will throw an error saying that $col[0]['short']
is not set.
Upvotes: 1