Array sum giving wrong value PHP - 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

Related

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.

comma separator using implode not working

i have a query getting the result inside my database and i'm using implode to get the result i want, my query is getting the sum of a column, the fetching works fine the only problem is that it shows me like this:
result:
14321
should be:
14,321
can somebody please help with it..
here is my code:
$res1 = $DB_con->query("SELECT sum(user_id) AS total FROM login");
$row = $res1->fetch(PDO::FETCH_ASSOC);
echo implode(',', $row);
I think here you don't need to used implode you can do like this way also.
$res1 = $DB_con->query("SELECT FORMAT((sum(user_id)),2) AS total FROM login");
$row = $res1->fetch(PDO::FETCH_ASSOC);
echo $row['total'];
You need to use format function of MySQL. More About format function
Here Is The Explanation why there is no need to used implode function.
Implode function is used for convert each array value with convert into string with some specific delimiter Here as per your query you are getting single result sum so on that single value you can't used implode. You just need use format function for format your number as you want. More About implode function

PHP function issues with array

I have a postgres table with four columns labelled dstart which is date data type,
dend which is also a date data type, dcontract which is a date data type and id which is a integer. I am trying to run a php code to get the data using an array and use it in the body of my application. But when I test the array and try to echo some values... My browser just displays the word array... Is there anyway I can be able to retrieve the data or fix this code? Please see code below
<?php
function getLiveDate($campid)
{
global $conn,$agencies;
$return=array(
'livedate'=>'',
'campid'=>'',
'enddate'=>'',
'dateContract'=>'',
);
$sql = "SELECT id, dcontract, dstart, dend
FROM campaigns
WHERE id = '".$campid."' ORDER BY dstart DESC LIMIT 1";
$r = pg_query($conn,$sql);
if ($r)
{
$d = pg_fetch_array($r);
if (!empty($d))
{
$return['livedate'] = $d['dstart'];
$return['campid'] = $d['id'];
$return['enddate'] = $d['dend'];
$return['dateContract'] = $d['dcontract'];
}
}
#pg_free_result($r);
return $return;
}
I am pretty sure, your array $d is "multi-dimensional" and pg_fetch_array() returns an array of arrays, because the result of SQL queries in general may contain multiple rows. You limited it to one row, but you certainly get the correct values by assinging $return['livedata'] = $d[0]['dstart']; or $return['livedata'] = $d['dstart'][0]; and so on (I am not familiar with that particularly function for I usually use MySQL instead of Postgre).
Besides, try echoing your data by means of print_r() instead of echo.
The $return variable is an array, if you want shows the content, you must use print_r or var_dump not echo.

Possible to grab desc limit 1 from a previous query and assign to variable?

Can I get the last result of the last position of a previous query without having to do an entire query again? That is, I already have a query that ends like this:
WHERE (stories.SID = :SID) AND (writing.approved = :approved) ORDER BY position ASC";
$stmt->execute();
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
What I want to do is reference that query and add desc limit 1 and then assign that result to a variable. Is there a way to something like
$last = $row->desc limit 1 ?
I know this is not remotely correct, but just giving an idea of what I want to assign to $last. If I have to redo the whole query then I will but just curious....
PHP has a builtin function end() that returns the last element of an array. Since PDOStatement::fetchAll() returns an array of rows, you can just get the last entry from this array.
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$last_row = end($rows);
See the PHP doc for the end() function.
a way to do this:
//get number of elements in array
$elements = count( $rows);
//get last element of zero based array
$last = $rows[$elements-1];

php count returning 1 not 0 from mysql_query when empty

I am trying to get a count and I am getting 1 instead of 0 from it. I have looked thoroughly though the web and this site. I have even been trying to figure it out on my own for a long time. I keep coming empty handed here.
So Basically what I am trying to do is make a like system for my users. I can get everything to work correctly the count works except for one thing. When they have liked it it returns 1 not 0 which it should be.
Here is my code for the count. I am not posting all the coding for security reasons and it really doesn't need to since its about the counting part not the rest.
$sql_like = mysql_query("SELECT * FROM posts WHERE mem2_id='$id' ORDER BY post_date DESC LIMIT 40");
while($row = mysql_fetch_array($sql_like)){
$like1 = $row['like_array'];
$like3 = explode(",", $like1);
$likeCount = count($like3);
}
So here is the code that determines the number. Any ideas what is wrong with this? Why its returning 1 not 0 when the item is empty?
// you do escape your id right??? (sql injection prevention)
$sql_like = mysql_query("SELECT * FROM posts WHERE mem2_id='$id' ORDER BY post_date DESC LIMIT 40");
while($row = mysql_fetch_array($sql_like)){
$likeCount = 0;
$like1 = trim($row['like_array']);
if ($like1) {
$like3 = explode(",", $like1); // exploding emtpy string would result in array('')
$likeCount = count($like3);
}
}
Calling explode on an empty string gives an array containing the empty string. This is one element, not zero.
I would suggest that you change your database design if possible so that you don't store the values separated by commas. Use a separate table instead.
If you can't change the database design you can handle the empty string separately.
count() returns the number of indexes in an array or something in an object (PHP: count - Manual).
if a string var is used rather than an array or object it returns 1. it has to get a null value in order to return 0.
you can give it a go by trying:
print count("");
and
print count(null);
You'll have better luck if you use explode() to break the sql output into an array and then run a check with an if statement. Something like the following:
$like3 = explode(',',$like1);
if (count($like1)=1 && $like1[0] == '')
// etc ..
I hope this helps

Categories