Why do I keep getting 'array' as the output of my query? [closed]
Question
I'm trying to make a query to output the number of entrants from a specific event. The table is named 'payments' and the id of the event is in the 'itemid' column. This is what I have created, but it doesnt seem to work in the browser, but works fine in phpMyAdmin. Everytime I load the page instead of seeing a number, I see 'Array' as the output of my query.
Fixed it:
$res = mysql_query("SELECT COUNT(*) AS entrants FROM payments WHERE itemid='Sample Event 1'") or die();
$row = mysql_fetch_array($res,MYSQL_ASSOC);
<?php echo $row['entrants']; ?>
Solution 4
include ("includes/db.php");
// Get data from the database for content
$res = mysql_query("SELECT COUNT(*) AS entrants FROM payments WHERE itemid='Sample Event 1'") or die();
$row = mysql_fetch_array($res,MYSQL_ASSOC);
and
<?php echo $row['entrants']; ?>
Works fine now.
OTHER TIPS
You keep getting an array because you fetch it as one with this:
mysql_fetch_array($entrant_query);
The fetch_array function will return the row AS an array.
There are a number of other ways to return a row from the database - though I am guessing the one you are looking for is fetch_row
You could try var_dump instead to see what you are returning.
<?php
$a = array(1, 2, array("a", "b", "c"));
var_dump($a);
?>
// output:
array(3) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
array(3) {
[0]=>
string(1) "a"
[1]=>
string(1) "b"
[2]=>
string(1) "c"
}
}
Lastly, the mysql_*
functions are deprecated, you might want to look at moving to PDO instead. It is much safer, more flexible and if you are just starting out, a much better option to learn.
Please check the documentation of
mysql_fetch_array($query);
http://pa.php.net/manual-lookup.php?pattern=mysql_fetch_array%28%29&scope=quickref
also try doing this code
$f1 = mysql_fetch_array($entrant_query);
//this will give u the print out of the associative array:
printr($f1);
//you can now access each variable of the associative array by
//where the associative that prinr output
foreach($f1 as $value){
echo $value;
}
The method mysql_fetch_array()
loads the query results into an array that you can then use to access your data from. You can loop through the array to extract all the data or you can access specific data directly.
Even if your query was to return the count of records, and return 1 field, you are calling the function mysql_fetch_array
so it is returning just that, an array of however many fields are in the row.
Normally if you did SELECT * from users
you would then go round and round until there were no more rows, however, just because your query returns 1 field, its just an array of 1 because that's the way it works.