1

I want to Count a number of elements in a MySQL Table with the PHP element count, but when i try to give out the result it print 'Resource id #5' which is of course the id for succeeded MYSQL srcipts. If I type it in the SQL console it says I have got Syntax Error (#1064). Thats my code:

<?php
$dbhost = >>hostname<<;
$dbuser = >>user<<;
$dbpass = >>password<<;
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
 die('Could not connect: ' . mysql_error());
}
mysql_select_db(>>database to be selected<<)
or die ("Database couldn´t be found");

echo mysql_query('SELECT COUNT(*) FROM table'); ?>

Which mysql_fetch_ do i have to use?

Thanks for any effords and a happy new year

Tim

  • 1
    did you checked this, http://stackoverflow.com/questions/6907751/select-count-from-table-of-mysql-in-php – Sugam Jan 01 '16 at 16:56
  • 1
    The `mysql_query` returns a resource object ( as stated in the error ) and cannot be printed directly. You need to access the records in the appropriate manner – Professor Abronsius Jan 01 '16 at 17:03
  • 1
    Also, definitely worth reading for security reasons: [mysql - Why shouldn't I use mysql_* functions in PHP?](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php) – Brandon White Jan 01 '16 at 17:08

2 Answers2

2

You have to fetch the result from the query.

$result = mysql_query('SELECT COUNT(*) AS count FROM table');
$row = mysql_fetch_assoc($result);
echo $row['count'];

You should also convert from the mysql extension to PDO or mysqli, but the basic structure is the same -- after performing a query you have to fetch the results as a separate step.

Barmar
  • 741,623
  • 53
  • 500
  • 612
0

If you just looking for:

Which mysql_fetch_ do i have to use?

Than you can try these:

mysql_fetch_assoc();
mysql_fetch_array();
mysql_fetch_object();

Side note: Also remember what Mr. Barmar said about the **PDO or mysqli_* **

devpro
  • 16,184
  • 3
  • 27
  • 38