Getting wrong number when counting rows in PHP [duplicate] - php

This question already has answers here:
MySQLi count(*) always returns 1
(4 answers)
Closed 5 years ago.
I have a table called quote in my database with 5 rows. However when I try to count the rows it always returns 1 instead of 5. I am using the code below:
$connection = mysqli_connect("host","username","password","database");
$querya = "SELECT COUNT(id) FROM quote";
$resulta = mysqli_query($connection, $querya);
$max = mysqli_num_rows($resulta);
$srow = rand(1,$max);
<br /> There are <?php echo $max ?> number of rows
I am counting the id column which is a primary key and therefore never null. I have also tried it by using count(*) but get the same result. Where am I going wrong?

You can't pair mysqli_num_rows with count. If you want to use mysqli_num_rows you'd have to select * (which would be slow). Instead select count(*) as total, and use total.

If you want to use COUNT() in your query give it an alias that you can return:
$querya = "SELECT COUNT(`id`) AS `Total` FROM `quote`";
$resulta = mysqli_query($connection, $querya);
$row = mysqli_fetch_assoc($resulta);
echo $row['Total']; // identifier here is the same as the alias in the query

Related

How to echo the correct number of rows of a table [duplicate]

This question already has answers here:
Row count with PDO
(21 answers)
MySQL - count total number of rows in php
(11 answers)
Closed 3 years ago.
Need the number of rows of a table.
$st = $db->query("select count(*) from images");
$total = $st->rowCount();
echo $total;
result - 1
The table images has 2430 rows.
How to get the correct number of rows?
using PDO you could use
$result = $con->prepare("select count(*) from images");
$result->execute();
$total = $result->fetchColumn();
echo $total;
assuming $con is your connection to db
from PHP doc
DOStatement::rowCount() returns the number of rows affected by the
last DELETE, INSERT, or UPDATE statement executed by the corresponding
PDOStatement object.
If the last SQL statement executed by the associated PDOStatement was
a SELECT statement, some databases may return the number of rows
returned by that statement. However, this behaviour is not guaranteed
for all databases and should not be relied on for portable
applications.
Using PHP and MYSQLi functions
$query = "select * from images";
$result = mysqli_query($db, $query);
echo mysqli_num_rows($result);
This will output the total number of rows in the table
Of Course this presupposes that a connection has already been established to the database using $db

SELECT COUNT(*) returns an object instead of an integer [duplicate]

This question already has answers here:
Count rows from results of a "mysql_query"
(9 answers)
MySQL - count total number of rows in php
(11 answers)
count number of rows in table using php
(6 answers)
How can I count the numbers of rows that a MySQL query returned?
(12 answers)
PHP SQL get SELECT COUNT(user) to variable
(5 answers)
Closed 4 years ago.
I have a database table timestamps_sessions containing timestamps of when a user begins an exercise on my webpage, and which is only updated when the user actually finishes it. Therefore, every row always has a value in the started column, but not always in the finished column. The latter is NULL by default.
My SELECT COUNT() statement works perfectly when I query it in Sequel Pro, and returns the correct integer of 11. That is to say: there are indeed only eleven rows that have values in both started and finished.
Yet when I execute it in PHP, it returns an object containing
{
current_field: null,
field_count: null,
lengths: null,
num_rows: null,
type: null
}
The statement I successfully query in Sequel Pro is the following:
SELECT COUNT(finished) FROM timestamps_sessions
The statement I unsuccessfully use in PHP is the following:
$sql = "SELECT COUNT(finished) FROM timestamps_sessions";
$result = $conn->query($sql);
$exercise['clears'] = $result;
There are several other SELECT queries being performed to the same database and same table without issue. It's only the COUNT() statement that seems to be malfunctioning.
What am I doing wrongly, and how should I do it instead?
My goal is to count the number of rows with a non-empty finished column, without passing on the actual data in order to preserve bandwidth. All I need is the integer.
First of all, $result is an object as expected. It's the result returned by the mysqli::query() method. Before you can access the data from this query, you need to fetch it. It will be easier if you give an alias to the count, as it will become easier to access the count.
$sql = "SELECT COUNT(finished) as cnt FROM timestamps_sessions";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$exercise['clears'] = $row['cnt'];
mysqli::query() docs
mysqli::fetch_assoc() docs
you have missing code mysql_fetch_array in order to fetch first record
$sql = "SELECT COUNT(finished) totals FROM timestamps_sessions";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$total = $row['totals'];
The argument passed to the count function can be anything, since you just want the number of rows, not their data.
SELECT COUNT(1) FROM timestamps_sessions WHERE finished IS NOT NULL;
$sql = "SELECT COUNT(finished) AS count_finished FROM timestamps_sessions";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
echo $exercise['clears'] = $row['count_finished'];
Give the count an alias like count_finished. Then from the result object you need to fetch the row. The row has your data in it.
Take a look at this https://www.w3schools.com/php/php_mysql_select.asp

Invalid use of group function with MAX [duplicate]

This question already has answers here:
How do I select an entire row which has the largest ID in the table?
(6 answers)
Closed 9 years ago.
My code gives me the following error:
Invalid use of group function
$query = mysql_query("SELECT `text` FROM `text` WHERE `id`=max(id)");
if(!$query)
die(mysql_error());
while($row = mysql_fetch_array($result))
{
echo $row['text'];
}
Where is my mistake?
If you want the row with highest id you could use:
SELECT text FROM text ORDER BY id DESC LIMIT 1
WHERE clauses affect individual rows, whereas HAVING clauses affect aggregations (results of GROUP BY clauses). Row criteria must be limited to the WHERE clause, aggregate functions (like MAX) must be used in HAVING clauses.
You could do this:
SELECT *
FROM text
WHERE id = (SELECT MAX(id) FROM text);

PHP, MySQL: how to select random records without RAND (attempt to avoid RAND()) [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to request a random row in SQL?
Because of a huge table I cannot use MySQL function RAND() and trying to avoid using RAND() this way:
$a = mysql_fetch_array(mysql_query("SELECT MIN(id), MAX(id) FROM table WHERE category_id='".$var."'"));
$id = rand($a[0],$a[1]);
$id2 = rand($a[0],$a[1]);
Which doesn't work, because: in $a I have the biggest and smallest ID with the respective category_id - that's ok.
The problem brings the rows with $id and $id2 - because there are used the minimal and maximal ID values, but PHP function rand() will take some random value between minimum and maximum - and there is a big probability, that the picked out record will not belongs into category_id.
So I would like to ask you about a way, how could I fix this example.
THank you
You could try this:
$row = mysql_fetch_assoc(
mysql_query(
"SELECT count(*) as count FROM table WHERE category_id='$var'"));
$randomrow = rand(0, $row['count'] -1);
$q = mysql_query("
SELECT * FROM table
WHERE category_id='$var'
LIMIT 1 OFFSET $randomrow");

Mysql Counting rows in a table and returning an integer [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Whats the best way to get total # of records in a mysql table with php?
When i run :
mysql_query("SELECT COUNT(col) FROM table");
I end up with something like this :
(Resource) mysql result #4
How can i only get an integer that represent the number of row in my table so that later i can use it to make a simpel check such as : $result < 10.
Many Thanks
You have two options.
Get the result from the resource returned by the count query:
$resource = mysql_query("SELECT COUNT(col) FROM table");
$count = mysql_result($resource,0);
Or, get the number of rows from the resource returned by the query (without count).
$resource = mysql_query("SELECT col FROM table WHERE col IS NOT NULL");
$count = mysql_num_rows($resource);
I would recommend that you use the first, the reason being is that it is unnecessary to extract all the data from the table when you only need the count.
Note I've added WHERE col IS NOT NULL on the second one in order to recreate the effect of count(col) as opposed to count(*), as it will only count the non-null values of col.
mysql_query returns a mysql resource. To get the query output use:
$result = mysql_query("SELECT COUNT(col) FROM table");
if (!$result) {
die('Error:' . mysql_error());
}
echo mysql_result($result, 0);
See more examples here: http://php.net/manual/en/function.mysql-query.php
EDIT
By the way, this will only count the number of rows with a non-null value in col. To get the total number of rows in the table, use count(*)
Two options.
SELECT COUNT(*)....
Do the normal query. And add this line after retrieving the resource.
$num = mysql_num_rows($resource);

Categories