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

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.

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.

php array to string conversion odbc_exec count

i'm still new towards php but after searching through multiple topics i can't seem to figure this one out.
$query2 = "SELECT COUNT(MAP_CODE2) FROM TCODE_MAPPING WHERE MAP_CODE2 = 'ABC123'";
$result2 = odbc_exec($connect,$query2);
echo $result2;
i have a query above that i'd like to use to get the total number of rows within the query that i've set, however for some reason i keep getting hit by the error
Array to string conversion in /var/www/html/xxx.php on line 85
Would highly appreciate if anyone could help out on what i'm doing wrong. Thank you!
Problem is:-
You are trying to echo a result-set object of array type.
Solution (check the code comments):-
$query2 = "SELECT COUNT(MAP_CODE2) AS MYCOUNT FROM TCODE_MAPPING WHERE MAP_CODE2 = 'ABC123'"; // given a name to the count
$result2 = odbc_exec($connect,$query2); //prepare and execute query
while (odbc_fetch_row($result2)) { //iterate over result-set object
echo odbc_result($result, "MYCOUNT"), "\n"; // echo count
}
What is happening here is you are echoing an array object type that is also a resource type and php echo only string and other primitive type variables.
so you need to use a loop to access the row or to get row count and access row just use a foreach($results as $result)
to get row count visit this sqlsrv-num-rows . on this official php link you can get more example how to fetch data.

Get count query results via getSingleScalarResult() and groupBy() - exception

I want get results of my query (with limit 10) + count possible results.
I know there is similar questions and answers.
for example here
but if i trying get count possible rows (via getSingleScalarResult()) i will get excepton: The query returned multiple rows. Change the query or use a different result function like getScalarResult().
$query = $repository
->createQueryBuilder('t')
->select('COUNT(t.katId)', 't.hotel', 't.title', 't.desc', 'picture', 'MIN(t.price) AS price');
$query->where('t.visible = (:visible)')->setParameter('visible', 1);
// + some wheres, where in, more than....
$query->groupBy('t.hotel');
$query->setMaxResults(10);
echo $query->getQuery()->getSingleScalarResult();
exit();
I just need one integer whitch represent all results from my query.
How can i get this count number? Ideal in one shot to db.
EDIT:
if i remove $query->groupBy('t.hotel'); and in select keep only ->select('count(t.katId)'); then it work. But i need groupBy because it makes real count of results.
SOLUTION
I divided it on two queries so - to get results i rolled back changes to state before trying any count information, and make clone this query (before set setMaxResults and groupBy), change select (keep all wheres) and get count information.
I will be grateful if someone offers better solution
Get results:
removed COUNT() from select
asking for results changed to 'normal' ->getArrayResults
Get count:
$q = clone $query;
$q->select('count(distinct t.hotel) as count');
$r = $q->getQuery()->getArrayResult();
echo $r[0]['count'];
exit();
If you need keep the groupBy:
$query = $repository->createQueryBuilder('t')
$query->select('COUNT(t.katId)', 't.hotel', 't.title', 't.desc', 'picture', 'MIN(t.price) AS price');
$query->from(ENTITY STRING, 't', 't.hotel'); //here defined your array result key
$query->where('t.visible = (:visible)')->setParameter('visible', 1);
$query->groupBy('t.hotel');
$query->setMaxResults(10);
echo $query->getQuery()->getScalarResult();
exit();
Edit : New edit works ?
You are only interested in COUNT(t.katId), so you should drop other returned fields 't.hotel', 't.title', etc.
The result will then contain a single return value (single scalar result), so $query->setMaxResults(10) is not needed.

Array sum giving wrong value PHP

What is wrong with this code?
$data455 = mysql_query("SELECT ROUND(SUM(gainloss), 4) FROM stats WHERE MONTH(date) = MONTH(CURRENT_TIMESTAMP) AND winloss = 'Win'");
$info455 = mysql_fetch_array($data455);
$testarray = array_sum($info455);
echo $testarray;
It does not display the correct sum. I want to get the sum of the last column where 'winloss' = 'win'
the output $testarray gives is 79.5843, but the correct sum is 41.6609.
Here is what my database looks like.
Try
mysql_fetch_assoc($data455);
Insted of
mysql_fetch_array($data455);
May this helps you because mysql_fetch_array returns both associative and indexing array you gets mixed result through it.
You don't have to use array_sum as in your query you already have the sum
$data455 = mysql_query("SELECT ROUND(SUM(gainloss), 4) AS total FROM stats WHERE MONTH(date) = MONTH(CURRENT_TIMESTAMP) AND winloss = 'Win'");
$info455 = mysql_fetch_array($data455);
echo $info455['total']; //this should give you the desired result
mysql_fetch_array by default returns the data from mysql as a numeric and associative array. You are essentially doubling your value by doing this. Change to mysql_fetch_assoc() and see what your result is.
http://php.net/manual/en/function.mysql-fetch-array.php
It is looks a problem of array sum. Looking at your SQL and the code line after that
$info455 = mysql_fetch_array($data455);
variable $info455 contains array something like
$info455['ROUND(SUM(gainloss), 4)'] = <some value>
$info455[0] = <some value>
So here your variable only holding one value twice. so array_sum will double the value. First try to see your SQL is giving the correct result and how many rows. If you want multiple rows from SQL and then sum using PHP then you have to iterate on the resultset

Sum variables in an array using while loop only 1 iteration per refresh PHP SQL

Hello stackoverflow, long time lurker first time asker. Anyways I am creating a project for my school and it is almost completely finished but I think I need help with the while loop. I am trying to sum the variables that are stored in the array and then output that into a useable variable that I can sum with another variable. The problem is the loop only does 1 iteration every time I refresh to page. So it will eventually get the full array but only one item at a time. Please let me know what I am going wrong, I'm sure its something dumb!
$bill= mysql_query("SELECT Transaction.date, Transaction.Price, Transaction.customer_customer_id, Service.cost, Service.user_id, Service.uname
FROM *.Transaction,*.Service
WHERE Transaction.customer_customer_id = Service.user_id AND Service.uname = '$uuname'");
$query_row=mysql_fetch_array($bill);
$userservice = ($query_row[cost]);
$userprice = ($query_row[Price]);
$row2=array();
while($row = mysql_fetch_array($bill))
{
$row2[] += $row['cost'];
}
$totalservice = array_sum($row2);
Thanks for any help you guys may have. This one is frying my brain.
Both your SQL and your PHP make no sense.
FROM *.Transaction,*.Service
...will throw an error in MySQL, but your code doesn't check for errors. I suspect it should be:
FROM Transaction, Service
While the PHP will parse and run.....
while($row = mysql_fetch_array($bill)) {
$row2[] += $row['cost'];
}
$totalservice = array_sum($row2);
Is a very strange way to populate an array. Why not just....
while($row = mysql_fetch_array($bill)) {
$totalservice+=$row['cost'];
}
Indeed, if you are just throwing away the rest of the data, then why are you fetching it from the database?
SELECT SUM(Service.cost)
FROM Transaction,Service
WHERE Transaction.customer_customer_id = Service.user_id
AND Service.uname = '$uuname'
In which case the join is also redundant:
SELECT SUM(Service.cost)
FROM Service
WHERE Service.uname = '$uuname'
Rewrite query as
SELECT Service.user_id, Service.uname, SUM(Service.cost) as cost
FROM djqrico_hotel.Transaction LEFT JOIN djqrico_hotel.Service ON Transaction.customer_customer_id = Service.user_id
WHERE Service.uname = '$uuname' GROUP BY Service.user_id
if you want to get sum of all user's transactions.
The problem is the loop only does 1 iteration every time I refresh to page.
Have you ran the query against the database and checked if it's returning more than one row?
Also, if all you want to do is sum the cost column you could do that in sql:
SELECT SUM(cost)[....]

Categories