comma separator using implode not working - php

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

Related

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.

Converting exploded array into string

In the project that I am creating, I have a mysql column that is an array of different pieces of data from the database. These pieces of data have info that I want to display. In order to separate these items in the array I used,
$get_query = mysql_query('Select array FROM data');
while($dataRow = mysql_fetch_assoc($getfrnd_query)) {
$array = $dataRow['array'];
if($array != "") {
$data_from_array_column = explode("," $array);
$getdata = mysql_query("SELECT * FROM info WHERE item = $data_from_array_column");
//Then I used a mysql_fetch_assoc to get data based on the item.
}
}
When I run this code, I get an error "Array to string conversion on the line with $getdata".
Is there any way to get this to work?
Thank you.
The problem is that explode returns an array containing the strings in between the character(s) you used as a delimiter (, in your case), not a string.
PHP is getting mad because it doesn't know how to convert your array to a string automatically. So, you will need to convert it yourself. The options are:
You want to select the row where item is equal to the nth element in the array, $data_from_array_column. If this is the case, you need to insert the following line of code after your explode:
$data_from_array_column = $data_from_array_column[0];
If you want to select where it matches any of the elements in the $data_from_array_column array, it will get more complicated. You would need to add this line after the explode:
$data_from_array_column = implode("' OR item='",$data_from_array_column);
and change your query on the next line to:
$getdata = mysql_query("SELECT * FROM info WHERE item='$data_from_array_column'");
This will create a MySQL query that looks some thing like this:
SELECT * FROM info WHERE item='foo' OR item='bar' OR item='bla'

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

How to do I get PHP and MySQL to return an integer using the MAX() function?

I have a database with a column of only numbers and i need to use php to access it and use the MAX() function to get the largest number, when i use the max function and then try to "echo" the value it says it isn't a string but an object. How would i fix this?
$nextnumber=mysqli_query($con,"SELECT MAX(videonumber) AS maxnum FROM videos");
echo ($maxnum);
fetch the row/object from $nextnumber and then print the associated value with maxmum. For an example,
$nextnumber=mysqli_query($con,"SELECT MAX(videonumber) AS maxnum FROM videos");
$row = $nextnumber->fetch_assoc();
echo $row['maxnum'];
mysqli returns a result object, you need to extract the value from there:
http://www.php.net/manual/en/class.mysqli-result.php
i suggest you use fetch_assoc() to get it with the expected name
$row = $result->fetch_assoc();
mysqli_free_result($result);
then you can access the value by name and print it:
echo($row["maxnum"])

Creating a json array using concat with MySql

I'm creating a json array from MySql data using concat like this:
$id = '5705';
$sql = 'select concat("{""type:""colName"",""id"":""$id""}") as myJson from table where etc.;
$stmt = $conn->prepare($sql);
What's happening is, instead of getting data from colName from the table and the value of $id, I'm getting the result as it is in $sql. How do I break out of it and get colName and $id's value?
Current Result
{""type:""colName"",""id"":""$id""}
Desired Result
{""type:""novice"",""id"":""5705""}
//Here novice is data from colName, and 5705 is the value of $id
Please DON'T DO THAT. Trying to format data into JSON in your SQL will be fragile as encoding things into JSON is subtly more tricky that you would expect and you will inevitably get it wrong.
You should use the json_encode function in PHP. It will work reliably whereas your code will almost certainly break.
$dataArray = array();
while($statement->fetch()){
$data = array();
$data['type'] = $typeColumn;
$data['id'] = $id;
$dataArray[] = $data;
}
json_encode($dataArray, JSON_HEX_QUOT);
Also, formatting data to send to a client really shouldn't be part of an SQL query.
You need a better concatenation either in query and php
'select concat("{""type:"",colName,"",""id"":""'.$id.'""}")
Despite it is not really needed you could surround column name with backticks `
Your variables inside your string are not substituted with their values, as you got single quotes. Double quoted strings will expand variables with their values
Thus, you could invert your quotes, like this, in order to get the actual values of your variables:
$sql = "select concat('...')"

Categories