简体   繁体   中英

SELECT COUNT(id) doesn't give me the right value

hello I'm on the finishline of writing a chat script. The only thing left is to compare how many messeges had the user seen with the total number in the database. Now the following line doesn't seem to work and I've been staring at it for an hour and can't find the cause.

$count = mysql_query('SELECT COUNT(id) as total FROM konsultaciq WHERE cat = "'.$_SESSION['key'].'" ');
echo count(total);

The echo gives me a value of "1", when there are 8 entries in the database under that "cat"

Change your code as below.

$count = mysql_query('SELECT COUNT(id) as total FROM konsultaciq WHERE cat = "'.$_SESSION['key'].'" ');
$res=mysql_fetch_array($count);
echo $res[0]; // it gives actual value of total
$count = mysql_query('SELECT COUNT(id) as total FROM konsultaciq WHERE cat = "'.$_SESSION['key'].'" ');
$arr = mysql_fetch_array($count);
echo $arr['total'];

Use above code. As you have not fetch the data by using mysql_fetch_* and if you will use the count function then it will show the 1 because of it is fetching one row.

count function is used to count the number of elements in array in PHP and there will be only one element.

so use $arr['total'] to get the value of total count of the query.

NOTE: mysql_* has been deprecated in the PHP's latest version. So use the mysqli_* or PDO.

You should not be using the MySQL extension. Here's an example using PDO instead

$pdo = new PDO('mysql:host=localhost;dbname=your_db_name;charset=utf8', 'username', 'password');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

$stmt = $pdo->prepare('SELECT COUNT(1) FROM konsultaciq WHERE cat = ?');
$stmt->bindParam(1, $_SESSION['key']);
$stmt->execute();

echo $stmt->fetchColumn();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM