Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display the results of a SELECT COUNT(*) in PHP

Tags:

sql

php

count

Current trying to display the results of a SELECT COUNT(*) from SQL within my website. I'm 100% new to PHP and SQL so understand this must be the basics! If anyone could recommend a good book or website to learn that would also be great.

Here is my current code:

<?php
include_once 'includes/db_connect.php';
include_once 'includes/functions.php';

sec_session_start();
$sql = ("SELECT COUNT(*) FROM project_directory");
$result = mysql_fetch_array($sql);
?>

<?php echo $result ; ?> 

The results are 28 and work if i run the following within the SQL box from phpMyAdmin

SELECT COUNT(*) FROM project_directory

Appreciate anyone help or advice.

like image 257
tgcowell Avatar asked Jan 23 '14 06:01

tgcowell


1 Answers

you did not execute the query using mysql_query() function.

you need to do like this

<?php
include_once 'includes/db_connect.php';
include_once 'includes/functions.php';

sec_session_start();

$sql = ("SELECT COUNT(*) FROM project_directory");
$rs = mysql_query($sql);
 //-----------^  need to run query here

 $result = mysql_fetch_array($rs);
 //here you can echo the result of query
 echo $result[0];

?>

<?php echo $result[0]; ?> 

Note: if you have started learning PHP/Mysql then try to use mysqli_* functions. mysql_ will be deprecated in future PHP versions.

like image 198
Jason W Avatar answered Oct 11 '22 19:10

Jason W