I have a PHP code which has the following output:
[{"stockdata":29655.88482666}]
And I need to change the code on my php to get the result in this format:
[{"data": [29655.88482666]}]
This is the code of my php:
<?php
function getArraySQL(){
$startd = "29964";
$endd = "29968";
$dsn = "prueba";
$connect = odbc_connect( $dsn, '', '' );
$query = "
Select SUM(TON_DESCARGADO) as stockdata
from
(Select unit,[load],enum_LOAD.[name],SUM(dumptons) as TON_DESCARGADO
from hist_dumps inner join hist_loclist on hist_dumps.shiftindex = hist_loclist.shiftindex
and hist_dumps.loc = hist_loclist.locid
inner join enum_LOAD on hist_dumps.[load] = enum_LOAD.[num]
where hist_dumps.shiftindex between '$startd' and '$endd'
GROUP BY loc,UNIT,unit#,[load],enum_LOAD.[name])TEMP1
where unit = 'Stockpile'
GROUP BY unit
order BY UNIT";
if(!$rs = odbc_exec($connect, $query)) die();
$rawdata = array();
$i=0;
while($row = odbc_fetch_array($rs))
{
$rawdata[$i] = $row;
$i++;
}
odbc_close( $connect );
return $rawdata;
};
$stockdata = getArraySQL();
echo json_encode(($stockdata), JSON_NUMERIC_CHECK);
What need to be changed to get the correct format? Should I do something to improve the code of my php?
How should I write it if I connect php to SQL server via PDO and get the same result? (just an optional doubt)
I don't find custom output in json_encode, so if you want to customize the output of array , you would need to prepare it.
I assumed the data exists at zero index (0).
So, I use $stockdata[0]
for JSON_NUMERIC_CHECK replace, used (float)
here is the preparation of output to send exactly you want.
$stockdata = getArraySQL();
$Numeric_data = (float) $stockdata[0];
$data = '[{"data": ['.$Numeric_data.']}]';
echo $data;
Demo
Related
I have a query that returns all the data while running at MSSQL, but when I try to get the result with php code it returns null
SELECT:
$query = "SELECT DISTINCT (E080SER.desser) as desser,
E080SER.CODFAM codfam, e085cli.apecli apecli,
E085CLI.CODCLI codcli, E085CLI.NOMCLI nomeCli
FROM
E160CTR,
E160CVS, e080ser,
E085CLI,
E070EMP,
E070FIL
WHERE
e070emp.nomemp like '%Gestão tech%' and
e080ser.codser = e160cvs.codser and
e080ser.codser like ('%manw%') and (E160CTR.CODEMP = 1) and
((E160CTR.CODEMP = E070FIL.CODEMP) AND (E160CTR.CODFIL =
E070FIL.CODFIL) AND
(E160CTR.CODCLI = E085CLI.CODCLI) AND (E160CVS.CODEMP =
E160CTR.CODEMP) AND
(E160CVS.CODFIL = E160CTR.CODFIL) AND (E160CVS.NUMCTR =
E160CTR.NUMCTR)) AND
(E160CTR.SITCTR = 'A') and e080ser.sitser = 'a' and
E080SER.CODEMP IN (1, 9)
order by e080ser.desser";
PHP CODE:
$sql = sqlsrv_query($conn, $query);
while($item = sqlsrv_fetch_array($sql)){
var_dump($item);
}
Sometimes it's necessary to fetch all result sets with sqlsrv_next_result() to get your data. You may try with this:
<?php
...
$sql = sqlsrv_query($conn, $query);
do {
while($item = sqlsrv_fetch_array($sql)){
var_dump($item);
}
} while (sqlsrv_next_result($sql));
...
?>
There is an extra semicolon after the while loop, i.e. the body of the loop is empty. Then the result you try to read is after the last row, that's why you don't get what you expected.
I've found the problem
The problem was the encoding, I put the $query inside of utf8_encode(), and now it is returning the results.
Thank you all for your time.
I have this script executing as a cron job everyday to update days remaining to pay invoices. I first query every row of my table and attempt to store the data in a multidimensional array but this seems to be storing everything I query in the first element of my array.
Here's my script:
<?php
include '../inc/dbinfo.inc';
ini_set("log_errors", 1);
ini_set("error_log", "/tmp/php-error.log");
error_log( "################################################# UpdateVendorInvoiceDays.php #################################################" );
$three = 3;
$fetchAllInvoices = "SELECT VENDORINVOICEID, VdrInvoiceReceived, PaymentDue, COUNT(*), DATEDIFF(PaymentDue, NOW()) FROM tblVendorInvoices WHERE VdrInvoiceStatusID != ?";
$getInvoices = $conn->prepare($fetchAllInvoices);
$getInvoices->bind_param("i", $three);
$getInvoices->execute();
$result = $getInvoices->get_result();
$rows = array();
$j = 0;
while($row = $result->fetch_assoc())
{
$rows[$j][] = $row;
$j++;
}
echo json_encode($rows[0][0]); //Only outputs one row
//UPDATE DAYS REMAINING IN EACH ENTRY THAT ISNT PAID
$updateDaysRemaining = "UPDATE tblVendorInvoices SET DaysRemaining = ? WHERE VENDORINVOICEID = ? AND VdrInvoiceStatusID ! = ?";
$setDays = $conn->prepare($updateDaysRemaining);
$k = 0; //incrementor
$numberOfEntries = $rows['COUNT(*)'];
for($k;$k<$numberOfEntries;$k++){
$setDays->bind_param("iii", $rows[$k]["DATEDIFF(PaymentDue, NOW())"],
$rows[$k]['VENDORINVOICEID'], $three);
if($setDays->execute()){
error_log('Cron success');
}else{
error_log('Cron fail');
}
}
?>
Currently the output from my first query is:
[[{"VENDORINVOICEID":88,"VdrInvoiceReceived":"2018-08-21","PaymentDue":"2018-07-27","COUNT(*)":2,"DATEDIFF(PaymentDue, NOW())":-25}]]
and my error log only gives me a notice for $rows['COUNT(*)'] being undefined (which makes sense)
I've looked at other answers here but they don't seem to have the same structure as I do.
EDIT: I also have 2 rows in my database but this only puts out one. I forgot to mention this.
There are a couple of simplifications to get all of the rows. Instead of...
while($row = $result->fetch_assoc())
{
$rows[$j][] = $row;
$j++;
}
echo json_encode($rows[0][0]);
You can just return all rows using fetch_all()...
$rows = $result->fetch_all (MYSQLI_ASSOC);
echo json_encode($rows);
Then encode the whole array and not just the one element - which is what $rows[0][0] was showing you.
As for you other problem - change in your select statement to
COUNT(*) as rowCount
and then you can use this alias for the field reference...
$rows['COUNT(*)']
becomes
$rows['rowCount']
I'm trying to fetch the comments inside the while loop by newsfeed_id, but it does not showing any result after first iteration. I print_r dynamically generated query its working fine but result does not showing.
$NewsfeedRes = array();
$Newsfeed = "select * from `ws_newsfeed` where `nf_status` = 1";
$NewsfeedQuery = mysqli_query($this->connection,$Newsfeed);
while($rowNews = mysqli_fetch_assoc($NewsfeedQuery)){
$NewsfeedRes[] = $rowNews;
$PushComment = "SELECT cmt.`cmt_id`,cmt.`cmt_comment`,cmt.`date_added`,
us.`u_username`,us.`u_image`
FROM `ws_comments` AS cmt
LEFT JOIN `ws_user` AS us ON cmt.`u_id`=us.`u_id`
WHERE cmt.`cmt_target_id` = ".$rowNews['nf_id']."
AND cmt.`cmt_table_name`='ws_newsfeed'";
//echo $PushComment; This giving me correct query
$PushCommentQuery = mysqli_query($this->connection,$PushComment);
while($rowPComment = mysqli_fetch_assoc($PushCommentQuery)){
$NewsfeedRes['comments'] = $rowPComment;
}
}
$output = array(
'NewsfeedRes' => $NewsfeedRes,
);
echo json_encode($output, JSON_PRETTY_PRINT);
Can any one guide me where I'm wrong that i can fix the issue. I will appreciate. Thanks
Every time you loop through your fetch comment loop you are resetting the the value of $NewsfeedRes['comments']. You need to push $rowPComment into an array.
If you want $rowNews and comment to be in the same array try:
while($rowNews = mysqli_fetch_assoc($NewsfeedQuery)){
$PushComment = "SELECT cmt.`cmt_id`,cmt.`cmt_comment`,cmt.`date_added`,us.`u_username`,us.`u_image` FROM `ws_comments` AS cmt LEFT JOIN `ws_user` AS us ON cmt.`u_id`=us.`u_id` WHERE cmt.`cmt_target_id` = ".$rowNews['nf_id']." AND cmt.`cmt_table_name`='ws_newsfeed'";
//echo $PushComment; This giving me correct query
$PushCommentQuery = mysqli_query($this->connection,$PushComment);
while($rowPComment = mysqli_fetch_assoc($PushCommentQuery)){
$rowNews['comments'][] = $rowPComment;
}
$NewsfeedRes[] = $rowNews;
}
If you want a seperate array for comments and news feed try:
while($rowNews = mysqli_fetch_assoc($NewsfeedQuery)){
$NewsfeedRes["newsfeed"][] = $rowNews;
$PushComment = "SELECT cmt.`cmt_id`,cmt.`cmt_comment`,cmt.`date_added`,us.`u_username`,us.`u_image` FROM `ws_comments` AS cmt LEFT JOIN `ws_user` AS us ON cmt.`u_id`=us.`u_id` WHERE cmt.`cmt_target_id` = ".$rowNews['nf_id']." AND cmt.`cmt_table_name`='ws_newsfeed'";
//echo $PushComment; This giving me correct query
$PushCommentQuery = mysqli_query($this->connection,$PushComment);
while($rowPComment = mysqli_fetch_assoc($PushCommentQuery)){
$NewsfeedRes['comments'][] = $rowPComment;
}
}
I just had a framework for creating charts and this is how it works normally.
$p = new chartphp();
$p->data = array(array(
array("A",2),
array("B",3),
array("C",23),
array("D",10)
));
$p->chart_type = "bar";
// Common Options
$p->xlabel = "My X Axis";
$p->ylabel = "My Y Axis";
$out = $p->render('c1');
This way it works perfectly fine, now I need to get results from a sql query and fill the array.
$query ="SELECT t.date AS dates,COUNT(t.id) AS trans FROM Gab AS g, Transaction AS t WHERE t.date BETWEEN '2015-07-30' AND '201-07-10' AND g.TID = '1401009' ORDER BY DATES";
$ask = mysql_query($query) or die("Error");
//Now I try to load the results into the array to be integrated into the API.
$p = new chartphp();
$p->data = array(array(
while($recon = mysql_fetch_array($ask)
{
array($recon['dates'],recon['trans']),
}
));
$p->chart_type = "bar";
// Common Options
$p->xlabel = "My X Axis";
$p->ylabel = "My Y Axis";
$out = $p->render('c1');
I tried this but it does not work, the array dont seem to be loaded !
I'm actually not sure what nesting a while like you have would do and I'm unable to experiment at the moment, but something like this should get you in the right direction:
$p->data = array(array());
while($recon = mysql_fetch_array($ask))
{
$p->data[0][] = array($recon['dates'], $recon['trans']);
}
Initializing the array and then appending the elements in the loop.
this is the code i use to generate single json object
$SQL = mysql_query("SELECT * FROM `receipts` WHERE DATE(date) = '2011-08-03'");
if(mysql_num_rows($SQL ) > 0){
$i=0;
$responce->success = true;
while($SQL_RESULT = mysql_fetch_object($SQL)){
$responce->data[$i]['reciept_no'] = $SQL_RESULT->reciept_no;
$responce->data[$i]['time'] = $SQL_RESULT->date;
$responce->data[$i]['user'] = $SQL_RESULT->user;
$i++;
}
}
else{
$responce->success = false;
$responce->data = '';
$responce->reason = "No Activity...";
}
echo json_encode($responce);
result is like
{"success":true,"data":[{"reciept_no":"2411","time":"09:33:56 AM","user":"test"},
{"reciept_no":"2412","time":"11:29:01 AM","user":" test "}]}
so there is another query which similar to this and generate exact same kind of output but from a another mysql table
i want to do is combine two results and send to javascript then decode it in javascript
like wrap first result with like table1 second result with table 2 or something
how to do that?
Sorry for the bad English
Regards
You could run both queries, one outputs to $response1 and the other to $response2, then you can use:
echo json_encode(array('table1'=>$response1,'table2'=>$response2));
JSON is just a text representation of a data structure. If you want to store two separate results in a single structure, then do
data['response #1'] = 'blah blah blah';
data['response #2'] = 'other other other';
You could store the two queries' data into a single sub-array, but then you'd need some extra data to be able to differentiate betweeen the two data sources. "did this record come from query #1? or from query #2?"
$SQL = mysql_query("SELECT * FROM `receipts` WHERE DATE(date) = '2011-08-03'");
if(mysql_num_rows($SQL ) > 0){
$i=0;
while($SQL_RESULT = mysql_fetch_object($SQL)){
$responce->data[$i]['reciept_no'] = $SQL_RESULT->reciept_no;
$responce->data[$i]['time'] = $SQL_RESULT->date;
$responce->data[$i]['user'] = $SQL_RESULT->user;
$i++;
}
}
$SQL = mysql_query("SELECT * FROM `receipts2` WHERE DATE(date) = '2011-08-03'");
if(mysql_num_rows($SQL ) > 0){
$i=0;
$responce->success = true;
while($SQL_RESULT = mysql_fetch_object($SQL)){
$responce->data[$i]['reciept_no'] = $SQL_RESULT->reciept_no;
$responce->data[$i]['time'] = $SQL_RESULT->date;
$responce->data[$i]['user'] = $SQL_RESULT->user;
$i++;
}
}
else{
$responce->success = false;
$responce->data = '';
$responce->reason = "No Activity...";
}
echo json_encode($responce);
Is that your question?