PHP SQL division by zero Warning but is not zero - php

I have a trouble.
I have a SQL table with processes which are finalized, closed, cancelled and working on, which also are associateds by an area (talent, outsourcing, digital, etc).
I want to do an AVG by the area and total by the states of the processes.
so i have:
$tiempoQueryFinalizados = mysqli_query($con,
"SELECT IFNULL(SUM(IFNULL(timestampdiff(DAY,fecha_creacion,IFNULL(fecha_cerrado,NOW())),0)),0) AS finalizados,
(Select count(id_proceso) from proceso where estado ='FINALIZADO' and fecha_cerrado is not null) as c
FROM proceso
WHERE estado = 'FINALIZADO' and fecha_cerrado IS NOT NULL and area ='".$rowArea['id_area']."' ");
Then I use a simple division in PHP with
mysqli_fetch_assoc($tiempoQueryFinalizados)['finalizados'] / mysqli_fetch_assoc($tiempoQueryFinalizados)['c']
but I get the error Warning: Division by zero, so I check if was zero but it doesn't. In this example mysqli_fetch_assoc($tiempoQueryFinalizados)['c'] = 2 but still counting as 0
any help, please?
EDIT: the area is returned by a fetch array of $areaQuery = mysqli_query($con,"SELECT * from area where id_area!=0");

This is not a simple division
mysqli_fetch_assoc($tiempoQueryFinalizados)['finalizados'] /
mysqli_fetch_assoc($tiempoQueryFinalizados)['c']
Each call to mysqli_fetch_assoc() gets a new row from your resultset. So as the query only returns one row, the second call will return FALSE which equates to zero.
So this would be a better way of doing the retrieval and calculation
$row = mysqli_fetch_assoc($tiempoQueryFinalizados);
$calc = $row['finalizados']] / $row['c'];

Ok I forgot when every call you do to mysqli_fetch* you are jumping to the next register, so only I needed to edit
$tiempoQueryFinalizados = mysqli_query(...
by
$tiempoQueryFinalizados = mysqli_fetch_assoc(mysqli_query(...
now
$tiempoQueryFinalizados['finalizados'] / $tiempoQueryFinalizados['c']
works very nice :)
thank you all!

Related

PHP calculation returns NAN

I'm trying to perform some calculation on Data retrieved from database ,
but evertime I run this code I get NAN as output.
function calculateNPS()
{
$queryTotal = "SELECT count(*) as total FROM message";
$resullTotal = mysqli_query($link ,$queryTotal);
$queryYes= "SELECT count(visit) as yes FROM message WHERE visit='Yes'";
$resultYes = mysqli_query($link ,$queryYes);
$queryNo = "SELECT *count(visit) as no FROM message WHERE visit='No'";
$resultNo = mysqli_query($link ,$queryNo);
$yescount = mysqli_fetch_assoc($resultTotal);
$nocount=mysqli_fetch_assoc($resultNo);
$totalcount=mysqli_fetch_assoc($resultYes);
$nps = ((float)($yescount['yes'])/(float)($totalcount['total'])*100)-((float)($nocount['no'])/(float)($totalcount['total'])*100);
echo $nps;
}
I hope thats just a test-script, because there are a lot of issues you could fall into ;-)
but your problem: i guess its just a typing-mistake. you name the result-var "resullTotal", below you are requesting another var called "resultTotal" ;-)
Some numeric operations can result in a value represented by the constant NAN. This result represents an undefined or unrepresentable value in floating-point calculations. So it seems you have some problems with the values in the $nps calculation.
I would suggest that you try outputting/inspecting all the params, like $yescount or $yescount['yes'] to make sure you have valid data to start with. Then break your expression into shorter operations until you find the issue.
For instance, mysqli_fetch_assoc returns an associative array that corresponds to the fetched row or NULL if there are no more rows.
Also, in your queries you use $link but I can't see where it's coming from.

how to subtract a specific amount from the COUNT(*) result

I'm new to PHP and i want to know how i can subtract a specific amount from the results from counting the total amount of rows in a table. In this case i'd like to minus the value 3 from whatever the value of the total rows is. But i keep getting an error. Below is my code.
$cartwork = $con->query("SELECT count(*) FROM table");
$vs = '3';
$camount = $cartwork - $vs;
echo "$camount";
When the code runs i get the error "Object of class mysqli_result could not be converted to int" what can i do to fix this and get it to work properly.
The query returns a result set. You need to parse through the result set(s) in order to access the values returned. That's basically what the error states.
Please see here for documentation on the PHP function for fetching rows:
http://php.net/manual/en/function.mysql-fetch-row.php
So basically you would need
$row=$cartwork->mysql_fetch_row();
$cartWork_value = $row[0];
$vs = '3';
$camount = $cartwork_Value - $vs;
echo "$camount";
Note - this assumes that you get back exactly one result row (which should be the case with your query).
You can simply change your query to:
$cartwork = $con->query("SELECT count(*)-3 FROM table");
It doesn't smell particularly good though.

table doesnt exist

I have created a query that loops through a group of table ID's to get a sum of their combined values. with error handling i get a "Table 'asterisk.custom_' doesn't exist" error and the query is killed obviously. but if i remove the error handling then i get an "mysql_fetch_array() expects parameter 1 to be resource" and the query completes as it should.
Thank in advance for your help.
include("currentday.php");
//---used for testing passing variables
//echo $customID[0];
//echo "<br>".$numrows;
$i = 0;
while($i<=$numrows)
{
mysql_select_db("asterisk") or die(mysql_error()); //This line determines the database to use
$query = "SELECT
vicidial_users.user,
vicidial_users.full_name,
sum(vicidial_agent_log.pause_sec) as sumPause,
sum(custom_$customID[$i].d_amt) as sumDamnt,
sum(custom_$customID[$i].up_amt) as sumUpamnt,
sum(custom_$customID[$i].md_amt) as sumMdamnt,
sum(custom_$customID[$i].s_amount) as sumSamnt,
sum(vicidial_agent_log.dispo_sec)
FROM
vicidial_agent_log
INNER JOIN
vicidial_users
ON
(vicidial_agent_log.user = vicidial_users.user)
INNER JOIN
custom_$customID[$i]
ON
(vicidial_agent_log.lead_id = custom_$customID[$i].lead_id)
WHERE
vicidial_users.user = 'tcx'
GROUP BY
vicidial_users.full_name
ORDER BY
vicidial_agent_log.event_time DESC
";
$queryResult = mysql_query($query);// or die(mysql_error());
while ($rowResult = mysql_fetch_array($queryResult))
{
$pauseResult[] = $rowResult["sumPause"];
$sumdamntResult[] = $rowResult["sumDamnt"];
$sumupamntResult[] = $rowResult["sumUpamnt"];
$summdamntResult[] = $rowResult["sumMdamnt"];
$sumsamntResult[] = $rowResult["sumSamnt"];
}
//print_r($pauseResult);
//echo $pauseResult[0];
$i++;
}
Update:
The table exist in the database:
custom_2346579543413
custom_5466546513564
they are created by the dialer software and im calling them from another query that provides me the numeric part of the table name so this query loops through the values in customID array to make the query, Thanks again
Update:
Sammitch, thank you for the suggestion, however they did not work.
Solution:
Thanks Marc, you confirmed a suspicion i had in that it was looping correctly but for some reason it was looping more times that there we keys. so i echoed $i to confirm and in fact it was it was outputting 0,1,2,3 and since i know there is only 3 keys the last one didn't return anything and so error handling caught it and killed the entire loop and why it appeared correct when error handling was turned off. The solution was actually rather simple and it was in the while loop evaluation string i had used
while($i<=$numrows)
while($i<$numrows)//this worked, the equals part of that gave it an extra loop
and the query completes as it should.
No, it doesn't. "mysql_fetch_array() expects parameter 1 to be resource" means "the query failed, and you didn't bother to check before calling mysql_fetch_array()".
Your problem is that variable expansion inside of a string doesn't like array indexes. You need to change:
"sum(custom_$customID[$i].d_amt) as sumDamnt,"
To:
"sum(custom_{$customID[$i]}.d_amt) as sumDamnt,"
Or:
"sum(custom_" . $customID[$i] . ".d_amt) as sumDamnt,"
For it to work properly.

php while loop failing inexplicably while fetching result rows

So I'm having a very strange issue and am not quite sure what to think about it...
I have a standard database query doing a select on a table. It returns a resource, num_rows = 101, and it will fetch rows up to row 42 at which point it simply stops all script execution, no errors, not timing out (takes less than a sec to get the 42 rows) ... I can't provide a link but here's the code in question...
$select2 = "SELECT * FROM `$dbname`.`$file" . "_settings` WHERE `weight` <> 0 ORDER BY `count` ASC";
$result = mysql_query($select2);
$lpcnt = 0;
$numrows = mysql_num_rows($result);
while ($display = mysql_fetch_array($result, MYSQL_ASSOC)){
/* This will print out 42 times */
echo '<pre>In The LOOP, row('.$lpcnt.'):<br>NumRows: '.$numrows.'<br>';
print_r($display);
echo '</pre><br/>';
$domRows[] = $display;
$aTotal[] = $display['count'];
$aTotWeight[] = $display['weight'];
//debug vars
$d['url'] = $display['url'];
$d['total'] = $total;
$d['count'] = $display['count'];
$d['weight'] = $display['weight'];
$dbug['domRows'][] = $d;
$lpcnt++;
}
/* Never Reaches this */
echo '<pre>';die(print_r('Loop Finished'));
At a loss as to what's causing the failure midway through the results loop...
also..I know, I know...myql_ is depreciated, but's that's what I have to work with!
Thanks in advance for any light anyone can shed...this is really hurting the site!
EDIT: also this doesn't break all the time, so far it seems to be related somehow to the number of results...for example, if I run through a result set that has 39 rows, it will proccess all of them...and it's consitently failing at 42 rows... on my tables that have 100+ records
EDIT FINAL: Ok figured it out! Turns out we had our memory limit to low, so it was trying to allocate an illegal amount of memory! So we upped it and now it works! Also I had my error reporting in a spot where it was being conditionally turned back off by other code...that's why I wasn't seeing errors! Duh... anyway, thanks for the stabs, to those that responded Merry x-mas and all that jazz...

mysql is not returning all the rows

This is the query I have:
$sqlw = "SELECT * FROM coverages where user_id='3828' ORDER BY sp_id ASC";
$resultw = mysql_query($sqlw);
$roww = mysql_fetch_array($resultw);
while ($roww = mysql_fetch_array($resultw)) {
echo $roww['sp_id']."<br>";
}
echo "TOTAL:".mysql_num_rows($resultw)."<br>";
As you can see its very basic
the results show : TOTAL:29
But when I count the list of the items returned back its only 28.
I ran the query on phpmyadmin it shows a total of 29 rows, I did count them and they are 29.
I ran different other simple queries and it always does the same thing: one row is missing. This could be trivial maybe I am missing something or maybe its server related? any help/ideas would be greatly appreciated. Thank you
Your call to mysql_fetch_array() before the loop disposes of a row.
You have a classic off-by-one error.
There is an extra $roww = mysql_fetch_array($resultw); before your loop starts. This means you're throwing away the first row.

Categories