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.
Related
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.
I am using PDO to execute a query for which I am expecting ~500K results. This is my query:
SELECT Email FROM mytable WHERE flag = 1
When I run the query in Microsoft SQL Server management Studio I consistently get 544838 results. I wanted to write a small script in PHP that would fetch these results for me. My original implementation used fetchAll(), but this was exhausting the memory available to php, so I decided to fetch the results one at a time like so:
$q = <<<QUERY
SELECT Email FROM mytable WHERE flag = 1
QUERY;
$stmt = $conn->prepare($q);
$stmt->execute();
$c = 0;
while ($email = $stmt->fetch()[0]) {
echo $email." $c\n";
$c++;
}
but each time I run the query, I get a different number of results! Typical results are:
445664
445836
445979
The number of results seems to be short 100K +/- 200 ish. Any help would be greatly appreciated.
fetch() method fetches one row at a time from current result set. $stmt->fetch()[0] is the first column of the current row.
Your sql query has no ordering and can have some null or empty values (probably).
Since you are controlling this column value in while loop, if the current row's first value is null, it will exit from the loop.
Therefore, you should control only fetch(), not fetch()[0] or something like that.
Also, inside the while loop, use sqlsrv_get_field() to access the columns by index.
$c = 0;
while ($stmt->fetch()) { // You may want to control errors
$email = sqlsrv_get_field($stmt, 0); // get first column value
// $email can be false on errors
echo $email . " $c\n";
$c++;
}
sqlsrv_fetch
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.
i am trying to add up some records from a table, however, it isn't working properly, i.e. when i try var_dump to see what the value is showing i just get string(0) ""
Here is the code
$current_wealth1 = mysql_query("SELECT SUM(estimated_wealth) as total_house_wealth FROM user_houses WHERE user_id='$user_id'");
var_dump($total_house_wealth);
$current_wealth = $ved_balance + $total_house_wealth;
In terms of output, i am just using conventional php print to output $current_wealth.
Any ideas, what could be the problem?
EDIT: Here is my current code, getting a syntax error on the second line
$current_wealth1 = mysql_query("SELECT SUM(estimated_wealth) as total_house_wealth FROM user_houses WHERE user_id='$user_id'");
$total_house_wealth = mysql_fetch_array($current_wealth1)[0];
$current_wealth = $ved_balance + $total_house_wealth;
You need of course to do
var_dump(mysql_fetch_array($current_wealth1));
Also most likely you get a syntax error becuase you don't have php 5.4. You can't do ...)[0];
try splitting the fetch array to 2 lines to remove your syntax error?
$current_wealth1 = mysql_query("SELECT SUM(estimated_wealth) as total_house_wealth FROM user_houses WHERE user_id='$user_id'");
$total_house_wealth = mysql_fetch_array($current_wealth1);
$total_house_wealth = $total_house_wealth[0];
$current_wealth = $ved_balance + $total_house_wealth;
also, in your table structure, is user id a character string, or integer? if its an integer, then the userid='$user_id' in the WHERE clause shouldn't be single quoted (e.g. userid=$user_id *although you may want to sanitize the user_id var first*)
$total_house_wealth isn't declare nor set with any value, so what you are seeing is expected behaviour. What you actually want is a different thing
$total_house_wealth = mysql_fetch_array($current_wealth1)[0];
I have been working on this for a while now, I know it's simpler than what I am making it, but I just can't get it. I have some code where I am trying to query an enum either 1 or 0 from my table so this is exactly what I have to do this.
$username = 'test'
$passResult = mysql_query("SELECT usrSetPass FROM members WHERE usr='.$username.'");
Now I have all the connection stuff down I think, I get no errors there, but when I print this thing out in my echo I get this,
Heres my echo:
echo 'Hello, '.$username.', you Result is: '.$passResult.'!';
What I want to get is:
Hello, test, your Result is: 1
or
Hello, test, your Result is: 0
Now what I get is:
Hello, test, your Result is: Resource id #6
Now no matter what I do I get the same thing, I have no idea what I'm doing wrong here guys if someone could point this out that would be awesome. What this enum is being use essentially for a boolean just to see if the user has personally set a password not the computer generated version.
mysql_query returns a result resource, essentially a pointer to the memory where the results are buffered. That result set can contain many rows, as you can select many rows, so you need to fetch the row(s) you want then the column(s) you want from those rows.
/* execute the query and get a result resource back */
$passResult = mysql_query("SELECT usrSetPass FROM members WHERE usr='" . mysql_real_escape_string($username) . "'");
/* retrieve the first row from $passResult */
$row = mysql_fetch_assoc($passResult);
/* assign the usrSetPass column's value from that row to $passed */
$passed = $row['usrSetPass'];
Also, your query is wrong. You enclosed it in double quotes, so you're not actually breaking out of the string and concatenating $username when you use the single quotes and dots inside. I've corrected it above.
mysql_query doesn't return a value, it returns a resource (see here in the manual).
The returned result resource should be passed to another function for dealing with result tables (like mysql_fetch_array() or mysql_fetch_assoc()), to access the returned data.
Example based on your initial code:
$username = 'test';
$passResult = mysql_query("SELECT usrSetPass FROM members WHERE usr='".$username."'");
while ($row = mysql_fetch_assoc($passResult)) {
echo $row['usrSetPass'];
}