select distinct using php gives wrong result [duplicate] - php

This question already has an answer here:
PDO prepared statement fetch() returning double results
(1 answer)
Closed 3 years ago.
mysql
select distinct(cat) from code order by cat asc;
result - 1 row selected
that's true - because entire cat column has the same value.
php
$st = $db->query("select distinct(cat) from code order by cat asc");
$st->execute();
$arr = $st->fetch();
echo count($arr); // 2
Why I'm getting two rows selected using php?

$st->fetch() just returns a single row, not all the rows. count($arr) is the number of elements in this array. The default fetch mode is PDO::FETCH_BOTH, so the array contains two elements for each column you selected.
["cat" => "Category Name", 0 => "Category Name"]
To get all the rows, use $st->fetchAll():
$rows = $st->fetchAll();
echo count($rows);
BTW, DISTINCT is not a function, and it doesn't just apply to a single column, so you shouldn't put parentheses after it. It's a keyword that applies to the entire SELECT list. There's no difference when you're only selecting one column, but it would be misleading to write something like SELECT DISTINCT(col1), col2 ....

Related

how to display mysql GROUP_CONCAT values in php without while loop [duplicate]

This question already has answers here:
Single result from database using mysqli
(6 answers)
Closed 1 year ago.
I have a table named profile like this
S/N Name Age (VALUES) (1, Julius, 5 ) (2, Mark, 7) (3, Ismael, 9)
I want to display a result that will fetch the name row and separate the values with comma, e.g.
$result = Julius, Mark, Isamel
I used
$resuk = mysqli_query($conn, "SELECT GROUP_CONCAT(Name) FROM profile;");
$get_info = mysqli_fetch_assoc($resuk);
$values = explode(",", $get_info);
echo $values;
This gave me below error
Warning: explode() expects parameter 2 to be string, array given in C:\xampp\htdocs\dowel\commasep.php on line
I would appreciate if someone can assist.
Thanks.
mysqli_fetch_assoc() function fetches a result row as an associative
array.
So your $get_info variable is basically a whole row, you need to explode the FIELD and NOT the whole ROW
You should be able to achieve this by assigning a column alias from your query result like so
mysqli_query($conn, "SELECT GROUP_CONCAT(Name) as AllNames FROM profile;");
And then you can access that column in the explode function like so
$values = explode(",", $get_info['AllNames']);

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

PDO rowCount only returning one [duplicate]

This question already has answers here:
Row count with PDO
(21 answers)
Closed 6 years ago.
I have a SELECT query, like this:
$stmnt = $conn->prepare("SELECT post_title, posts_cat FROM posts WHERE posts_cat=:posts_cat");
$stmnt->execute(array(':posts_cat' => $cat_id));
$post_info = $stmnt->fetch();
$count = $stmnt->rowCount();
If there are no posts it shows none, but if there's one or more then it displays only one.
Can someone tell me why this is?
PDOStatement::rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed by the corresponding PDOStatement object.
rowCount() is not for a SELECT query, use a separate COUNT query for that or fetch all rows in an array and count its size
Please do not use rowCount() with select query
use a different query with count() for counting rows
$sql = "SELECT count(*) FROM `posts` WHERE posts_cat = :posts_cat";
$stmnt = $conn->prepare($sql);
$stmnt->execute(array(':posts_cat' => $cat_id));
$count = $stmnt->fetchColumn();
Of course you are getting the right number of rows returned. 1 means that only one row was found. If you want more rows to be found, add more rows to your database to match the condition.
Whether you need such a function at all - is another question, already answered in this post

PHP - Return count(*) results [duplicate]

This question already has answers here:
How to get the total number of rows of a GROUP BY query?
(11 answers)
Closed 8 years ago.
How can I return the number of counted rows with PDO?
This is my code:
$n=$dbh->prepare("SELECT count(*) FROM users_notifications WHERE userid=0 OR userid=:userid");
$n->bindParam(":userid",$userdata['id']);
$n->execute();
$notifications = count($n);
This returns just 1. Although there are 2 results when I run the query in the database: SELECT count(*) FROM users_notifications WHERE userid=0 OR userid=:userid
The count SQL function is an aggregate function that returns one row with the number of rows matching the where clause.
PHP's count returns the number of rows in a result set, which, as illustrated in the previous paragraph, should be one. Instead, you should retrieve the value of the result column. E.g.:
$n=$dbh->prepare("SELECT count(*) as c FROM users_notifications WHERE userid=0 OR userid=:userid");
$n->bindParam(":userid",$userdata['id']);
$n->execute();
$result = $n->fetch(PDO::FETCH_ASSOC);
$notifications = $result['c'];

Query returning additional empty variable

I'm running into some weird behaviour when calling values with SQL.
$result = mysqli_query($conn,"SELECT DISTINCT value FROM table ORDER BY value ASC");
while($row[] = mysqli_fetch_array($result));
$maxcat = count($row);
There are 8 unique values in my table, yet $maxcat returns "9". Am I missing something? I'm using the information to populate a list of categories. I knew I'd have to subtract one from maxcat to allow for $row[0], but I'm having to subtract two to make up for this empty value that won't get lost.
for ($i=0; $i<=($maxcat-2); $i++)
Cheers!
Thanks #scrowler & #faintsignal! Using mysqli_num_row() rather than count() is exactly what I needed. Functioning code below.
$result = mysqli_query($conn,"SELECT DISTINCT value FROM table ORDER BY value ASC");
$maxcat = mysqli_num_rows($result);
while($row[] = mysqli_fetch_array($result));
The while condition gets evaluated once for every row in your query result, plus one additional time to detect that there are no more rows left. So if you have 8 rows in your result, the while condition is evaluated 8 + 1 = 9 times. Hence you add 9 entries to your array $row, the final entry having the value NULL.
Note, if your while loop had a body, that body would only be iterated 8 times because the 9th time the condition would evaluate to false.
As #scrowler pointed out, if you just want to count the number of rows in the result, you can simply use mysqli_num_rows.

Categories