0

I am trying to display the number of rows I have in my database, but instead of the number being displayed on my page I just get the word 'array'

My code is below

$productCountSql = "SELECT COUNT(*) FROM products WHERE `user_id` = '" . $_SESSION['user_id'] . "'";
		$productCountResult = mysql_query($productCountSql);
		$countProducts = mysql_fetch_assoc($productCountResult);
		echo "<tr><td>Products uploaded:</td><td>$countProducts products</td></tr>";

If anyone can point me in the correct direction that would be great. Thankyou

2
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by lit108
1

The result sets are always an array. Even if it contains one column.

A couple minor changes are needed:

$productCountSql = "SELECT COUNT(*) as rowcount FROM products WHERE `user_id` = '" . $_SESSION['user_id'] . "'";
$productCountResult = mysql_query($productCountSql);
$countProducts = mysql_fetch_assoc($productCountResult);
echo "<tr><td>Products uploaded:</td><td>{$countProducts['rowcount']} products</td></tr>";

In the sql query I assign the count result an alias. This alias becomes the column name and lets you easily get at the result in PHP. Otherwise it shows up as index 0 or something hard to read later.

Then in the echo I reference the array with the index name I created in the query. Because this is an array with an index within quotes, the expression is wrapped in {curly braces}.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.