PHP/Database: Find out how many rows have content - php

I have a SQL-statement like this:
$stmtTHIS = $db->query("SELECT titel, done_date FROM task WHERE project = $tID ");
How can I find out how many rows have an content in "done_date"?

First you have to define what "have content" means then just write a WHERE clause to find those. And use the COUNT function to count the number of rows returned. So lets say "have content" means the field is not null.
SELECT COUNT(*) FROM task WHERE project = $tID AND done_date IS NOT NULL
This counts all the records with that project id and have a value for done_date.
You may also want to check that done_date does not have some other empty value like empty string or 0.
AND done_date != "" AND done_date !=0
Alternate:
Use the query you have to get all those rows, then do the count in PHP:
$stmtTHIS = $db->query("SELECT titel, done_date FROM task WHERE project = $tID ");
$count = 0;
while($row = $stmtTHIS->fetchAssoc()){
//You probably want to do other stiff with the data
if( !empty($row['done_date']) ){
$count++;
}
}
echo $count;
Your code might be slightly different depending on the DB library your using, (I assumed mysqli)

Related

How to count a column in database and if empty return 0 PHP

I have a table where I want to count total entries in one column. But if the entire column is empty, I want the count to return 0 (meaning there are zero entries)
This is what I tried, but when I use echo it returns blank. In the database it is blank, but I want it to return 0 when column recall is empty.
CODE:
$chartsql = "SELECT recall from report where child_id='$childId'";
$ChartRes = mysqli_query($con,$chartsql);
while ($ChartRow=mysqli_fetch_array($ChartRes)){
$recall[] = $ChartRow['recall1'];
}
foreach($recall as $index=>$value) {
if($value === null) unset($recall[$index]);
}
$count_recall = count($recall);
if($count_recall = ''){
$count_recall1 = 0;
}
echo $count_recall;
Also, in the recall column, there are null entries as well as blank entries. So I want to ignore the nulls, but if all other entries are blank then it should return zero. If there are some blank and some valid entries, then it should only count the valid entries and not what is blank.
It should only return 0 if it is completely empty, ignoring nulls.
Use SQL count function instead:
$chartsql = "SELECT count(child_id) as totalitems from report where child_id='$childId' and recall is not null and recall != ''";
$ChartRes = mysqli_query($con,$chartsql);
$ChartRow = mysqli_fetch_array($ChartRes);
$count_recall = $ChartRow['totalitems'];
Never use PHP for counting, when you can use SQL for your result, because:
When you have many rows, you will have performance issue.
You can easily do it inside your query and have cleaner codes.
Debugging is much easier.
How about count(*)
https://dev.mysql.com/doc/refman/8.0/en/counting-rows.html
$chartsql = "SELECT count(*) from report where child_id='$childId'" and recall is not null and recall != ''";
<?php
$chartsql =
"SELECT (count(id) - (
SELECT count(id)
FROM report
WHERE attributeName LIKE ''))
FROM report";
?>
All you need to do is substract the total of rows to the amout of empty rows. It should do the job
In PHP you could simplify it by:
assign only valid value to $recall array
add zero to returned value from count() to make it an integer
<?php
$chartsql = "SELECT recall from report where child_id='$childId'";
$ChartRes = mysqli_query($con,$chartsql);
while ($ChartRow=mysqli_fetch_array($ChartRes)){
if(!is_null($ChartRow['recall1'])){
$recall[] = $ChartRow['recall1'];
}
}
$count_recall = count($recall) + 0;
echo $count_recall;

Using Count giving wrong number of rows

Before I was using this code to count rows
echo $db_handle->numRows("SELECT * FROM orders WHERE DATE(reattemptdate) = CURDATE()");
than i found it effects on performance, than i tried to use below code, but it not giving correct number of rows, what wrong i done in below code ?
$sqldelivery = "SELECT COUNT(*) as count FROM orders WHERE DATE(reattemptdate) = CURDATE()";
$resultdeliverys = $db_handle->runSelectQuery($sqldelivery);
$numrowsresultdelivery =count($resultdeliverys);
echo $numrowsresultdelivery;
Database connection code :
function numRows($query) {
$result = mysqli_query($this->conn,$query);
$rowcount = mysqli_num_rows($result);
return $rowcount;
}
In your second code, the query will always return 1 row - a row with the column count being the number of rows, so...
$numrowsresultdelivery =count($resultdeliverys);
Will probably always be 1, you need something like...
$numrowsresultdelivery =$resultdeliverys[0]['count'];
to extract the count field from the first row of the result.
(Note I don't know if this is the right notation, but it's the principle of needing a field from the result rather than the number of results.)
You must already have the count number via $resultdeliverys->count.
$sqldelivery = "SELECT COUNT(*) as count FROM orders WHERE DATE(reattemptdate) = CURDATE()";
$resultdeliverys = $db_handle->runSelectQuery($sqldelivery);
// Try this to know if it's returning array or object
var_dump($resultdeliverys);

Count rows, or keep int field for counting?

When I want to find out how many shoes Alfred has, I always count the rows in the table "usershoes" where the userid matches Alfred's
But since I switched to PDO, and select row count is not simple or bulletproof/consistent, I'm reconsidering my methods
Maybe I should instead keep an int field "shoes" directly in table "users", keep number of shoes there, and then increase/decrease that number for that user along the way? Feels not right..
If anyone has a solid method for simple row counting on an existing select query, without extra query, let me know
Try something like this
SELECT COUNT(*) FROM usershoes
WHERE userid="theIdOfTheUser";
I could not get count(fetchColumn()) or fetchColumn() to work correctly (outputted 1 when 0 was the real number)
So now I'm using this, and it works:
$sql = 'SELECT COUNT(*) as numrows, shoecolor FROM usershoes WHERE userid = ?'
$STH = $conn->prepare($sql);
$STH->execute(array($someuseridvar));
And then:
$row = $STH->fetch();
if ($row['numrows'] > 0) {
// at least one row was found, do something
}
With MySQL, you can use FOUND_ROWS():
$db = new PDO(DSN...);
$db->setAttribute(array(PDO::MYSQL_USE_BUFFERED_QUERY=>TRUE));
$rs = $db->query('SELECT SQL_CALC_FOUND_ROWS * FROM table LIMIT 5,15');
$rs1 = $db->query('SELECT FOUND_ROWS()');
$rowCount = (int) $rs1->fetchColumn();
$rowCount will contain the total number of rows, not 15.
Taken from:
http://php.net/manual/en/pdostatement.rowcount.php#83586

Update table with increment value

Im trying to update a value in a table, using while loop, but i want this value to be like using auto_inc key.
My table: ID / CAR_ID / IMG_KEY / IMAGE
i want to take 12 rows of the same CAR_ID and give the IMG_KEY values from 1-12.
I tried the below loops, but the result is giving the IMG_KEY the value 1
$getImages = mysql_query("SELECT * FROM more_images WHERE car_id = '$car_id'") or die(mysql_error());
$img_key = 0;
for ($img_key = 1; $img_key <= mysql_num_rows($getImages); $img_key ++) {
while ($selectedImages = mysql_fetch_assoc($getImages)) {
$update = mysql_query("UPDATE `more_images` SET `img_key` = '$img_key' WHERE `car_id` = '$car_id'") or die(mysql_error());
}
}
The goal is give to the following 12 rows img_key values from 1 to 12 and all the other values as they are.
Ok, I'm still not 100% sure what you want, but my guess is that you are looking for something like this:
$imgKey = 0;
while ($selectedImages = mysql_fetch_assoc($getImages))
{
$imgKey++;
$update = mysql_query("UPDATE `more_images` SET `img_key` = '{$imgKey}' WHERE `car_id` = '{$car_id}'") or die(mysql_error());
}
In your question, your for loop isn't doing anything other than looping, in your case it iterates twelve times.
Since mysql_fetch_assoc($getImages) is a function that loops through all rows in a set of results. So for each iteration of your for loop, it updates all records to have the same $img_key.
Also, really do refrain from using mysql_* functions, they're deprecated. Read this thread:
Why shouldn't I use mysql_* functions in PHP?

Loop Through Records, Update one Record, and Exit

I want to select all records from my table and loop through all those records until I get to the record where the numtimespaid column is equal to 0. Once I find that column I want to update it to 2 for that record and then exit out. Here is what I have that is not working correctly:
$query1 = "SELECT * FROM ".$line." ORDER BY datestamp, timestamp";
$result1 = mysql_query($query1) or die(mysql_error());
while($row = mysql_fetch_array($result1)){
if ($row[numtimespaid] == 0) {
$queryupdate="UPDATE ".$line." SET numtimespaid=1";
$resultu=mysql_query($queryupdate);
break;
}
}
Any ideas as to what I'm doing wrong and/or the right way of doing this?
There is no need whatsoever to loop over rowset from a SELECT statement. You can simply update the first row with that value. This query will update exactly one record matching numtimespaid = 0. If you want to update all rows matching that criterion, just remove the LIMIT 1.
$result = mysql_query("UPDATE $line SET numtimespaid=1 WHERE numtimespaid = 0 ORDER BY datestamp, timestamp LIMIT 1");
By the way, we don't know what the contents of $line are, but hopefully you have properly filtered that value if it comes from user input. If it does comes from user input, it's recommended to check its value against a whitelist of possible table names:
// $line can be one of table1,table2,table3
if (!in_array($line, array('table1','table2','table3')) {
// FAIL, don't execute the query
}
if ($row[numtimespaid] == 0) {
Generally gets interpreted as numtimespaid being an undefined constant. Put quotes around it, like this:
if ($row['numtimespaid'] == 0) {
Then, realize Michael's answer is just better overall.

Categories