Display number of duplicates from database [SQL] - php

This is my code.
$sqlcount = "SELECT count(*) AS C, Horse_ID FROM images WHERE Horse_ID = 24 GROUP BY Horse_ID HAVING COUNT(*) > 1 LIMIT 0, 30";
//echo $sqlcount;
$resultcount = $conn->query($sqlcount);
$rowcount = $result->fetch_assoc();
echo $rowcount['C'];
Why won't it echo the number 4, which is what shows when I test it in phpmyadmin? There are 4 duplicate values in that table hence the 4.

$rowcount = $result->fetch_assoc();
to
$rowcount = $resultcount->fetch_assoc();

If you want the number of duplicates in the database, why not write the query to get that value?
SELECT COUNT(*)
FROM (SELECT count(*) AS C, Horse_ID
FROM images
WHERE Horse_ID = 24
GROUP BY Horse_ID
HAVING COUNT(*) > 1
) i;
Then, you will only be returning one value from the database to the application (which is faster) and there is no need to artificially limit the count to 30.

Related

How to count contents of last n rows mysql

I am trying to figure out how to see how many times in the past 7 entries/rows that sleep = 1.
Currently, $num shows the number of times sleep = 1 in all rows. I have seen that 'order by xxx desc limit 7' has been suggested in other answers but it doesn't seem to work well in this scenario. Would greatly appreciate any help, thanks!
Heres my code:
$result = mysqli_query($conn, "SELECT count(*) FROM test_table WHERE sleep = 1");
$row = mysqli_fetch_row($result);
$num = $row[0];
You can try this one:
SELECT a, COUNT(b) FROM test_table
WHERE sleep = 1
GROUP BY a
ORDER BY COUNT(b) ASC
LIMIT 7
Here, a is the name of your column you are trying to count
And, b is any column name for usage to count (it can id, or any column name)
If the sleep is binary/tinyint you can just sum that in the query with the order by.
SELECT sum(sleep)
FROM table
ORDER BY COUNT(id) DESC
LIMIT 7
If sleep isn't binary you can use a case statement.
SELECT sum(case when sleep = 1 then 1 else 0 end) as totalsleep
FROM table
ORDER BY COUNT(id) DESC
LIMIT 7
Here's my idea, get all the data in test_table and create a loop that will count the sleep, like this
$result = mysqli_query($link, "SELECT sleep FROM test_table;");
$x=1;
$sleep = [];
$SleepCount= 0;
while($row = mysqli_fetch_array($result)) {
if($row[0] == "1"){
$SleepCount++;
}
if($x == 7){
array_push($sleep,$SleepCount);
$SleepCount = 0;
$x=0;
}
$x++;
}
echo "<pre>",print_r($sleep),"</pre>";

get records between from a start to end number [duplicate]

This question already has answers here:
PHP & MySQL Pagination
(4 answers)
Closed 4 years ago.
This SQL return all records as (JSON) from 2 tables "posts_main" and "posts_comments" that depends on specific User
$sql = "select posts_main.*,
(select groupid from posts_comments where groupid = posts_main.id group by groupid ) as count_comments
from posts_main
WHERE posts_main.user_id = '$user_id' ";
$obj = json_decode($_GET["x"], false);
$stmt = $con->prepare($sql);
$stmt->bind_param("ss", $obj->table, $obj->limit);
$stmt->execute();
$result = $stmt->get_result();
$outp = $result->fetch_all(MYSQLI_ASSOC);
echo json_encode($outp);
My Question:
how can I get the first 10 records, then the next 10 records, to the end?
For example:
I'll send "start" = 0, I'll get the first 10 records.
Next time I'll send: "start" = 10, then I'll get the records FROM 10 TO 20.
and so on.
Thank you...
If you have a "start" number, you can frame your query like this -
$sql = "select posts_main.*,
(select groupid from posts_comments where groupid = posts_main.id group by groupid ) as count_comments
from posts_main
WHERE posts_main.user_id = '$user_id' limit 10,10";
MySQL reads 10 records starting at the 11th record in the table.
If you are looking for a Prev, Next solution then PHP pagination is the only option.
Hope this helps you:
$start = 0;
$sql = "select posts_main.*,
(select groupid from posts_comments where groupid = posts_main.id group by groupid ) as count_comments
from posts_main
WHERE posts_main.user_id = '$user_id'
limit '$start' 10";

Count the number of values that are bigger than 20

I have a table in my database, tbl. In that table I have id and num, both as regular int values.
I want to count how many IDs have num that is bigger than 20 (num > 20). Just to count how many rows have num > 20. I wrote this:
$counter= 0;
$sqlQuery = "select num from tbl";
$finalResult= $databasename->prepare($sqlQuery );
$finalResult->execute();
$numArr= $finalResult->fetchColumn();
foreach ($numArra $row){
if($row > 20)
$counter++;
}
echo ($counter);
The problem is, that it prints 0 everytime... Thanks in advance.
You don't need any of this. Just do
SELECT COUNT(*) FROM tbl WHERE num > 20
If you want to plug that into PHP and if you want to do this dynamically.
$finalResult= $databasename->prepare("SELECT COUNT(*) FROM tbl WHERE num > ?");
$finalResult->bindParam(1,$someParam);
$finalResult->execute();
$numArr = $finalResult->fetchColumn();
echo ($numArr);
Much simpler

How could I execute this basic table query in PHP?

Suppose I have a table TABLE:
NAME ID ...
m -1 ...
f -1 ...
g -1 ...
b -1 ...
z -1 ...
And I want to turn it into:
NAME ID ...
f 1 ...
g 2 ...
m 3 ...
b -1 ...
z -1 ...
You probably get the idea:
select the first 3 rows from the original table (preserving order)
order selected rows by the NAME column.
update selected rows' IDs with their position in the new table (keeping the remaining unselected rows in their original positions).
So (m, f, g) got sorted to (f, g, m) and (b, z) remained (b, z).
Here's how I am trying to do it in PHP:
$count = 0;
$query = "UPDATE TABLE SET ID = $count:= $count + 1 ORDER by NAME DESC LIMIT 3";
mysqli_query($con, $query);
But I don't think I can just go ahead and increment a counter and store its value like that. Any advice?
You can try this :
$limit = 3;
for($count = 0 ; $count < $limit;$count++ ){
$query = "UPDATE TABLE SET ID = $count + 1 WHERE ID = '-1' ORDER by NAME DESC";
mysqli_query($con, $query);
}
$query = "UPDATE TABLE SET ID = '-1' WHERE ID > $limit ORDER by NAME DESC";
mysqli_query($con, $query);
In the above logic :
In the final loop, all the IDs are set to $limit
However the update command outisde the loop will set back IDs to -1 again
First, you can quickly query for the first 3 rows in the table and get the name property only and assign the value in an array.
$sql = "select name from table order by name limit 3"
$query = $mysqli->query($sql);
Now let's construct a helper array:
while ($row = $mysqli->fetch_assoc()) {
$a[] = $row['name'];
}
Now just structure the queries:
foreach($a as $id => $name) {
$query = "update table set id={$id+1} where name='$name' limit 1";
// execute the query
}
Note that I assume that the name is unique so I added the limit 1 directive to tell it stop looking for rows to update once it has found a row.
Also, don't forget that array keys are counting starting from 0, hence we are adding 1 to the $id in the loop.
There may be more elegant solutions but this one is rather easy to understand and use.
In MySQL:
SET #row_number = 0;
update TABLE d
join
(
select
NAME,
#row_number:=#row_number+1 as ID,
from
(select NAME from TABLE limit 3) t
order by
NAME asc
) s on s.NAME = d.NAME
set d.ID = s.ID;
SQLFiddle: http://sqlfiddle.com/#!9/dffecf/1
This assumes NAME is your unique key, otherwise likely best to replace with an Identity column in your table and use that for the update.
This approach may require some syntax changes depending on your DB engine. By doing this in SQL, we only make one pass at the DB. Not a huge deal to iterate in multiple passes with PHP if you're only updating three records, but if it was a 1000, etc.

Get values from database from row to row

I'm trying to select values from row 85 in this while loop.
So all values that are selected in the database before row 85 should be excluded in the while loop, and everyone above 85 should be "Do Something" with.
Any suggestions how to achieve this?
$to_emails = mysql_query("SELECT * FROM ".$DBprefix."users WHERE workouts > 10");
while ($to_email = mysql_fetch_array($to_emails)) {
// Do Something
}
Look here:
To retrieve all rows from a certain offset up to the end of the
result set, you can use some large number for the second parameter.
This statement retrieves all rows from the 96th row to the last:
SELECT * FROM tbl LIMIT 95,18446744073709551615;
http://dev.mysql.com/doc/refman/5.0/en/select.html
So try something like this:
$to_emails = mysql_query("
SELECT * FROM ".$DBprefix."users
WHERE workouts > 10
LIMIT 85,18446744073709551615");
Try like
$to_emails = mysql_query("SELECT * FROM ".$DBprefix."users WHERE workouts > 10 LIMIT 85,200");
Or even try like(May be it works)
$to_emails = mysql_query("SELECT * FROM ".$DBprefix."users WHERE workouts > 10 LIMIT 85,(SELECT COUNT(*) FROM ".$DBprefix."users");

Categories