load mysql to json for NVD3 - php

<?php
$username = "root";
$password = "pw";
$host = "localhost";
$database="dbname";
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);
$myquery = "
SELECT `name`, `useTime`, `e_usage` FROM `electric_usage`
";
$query = mysql_query($myquery);
if ( ! $query ) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
echo json_encode($data);
mysql_close($server);
?>
I use upper php source to load mysql to JSON
the result of php page is
[{"name":"LED STAND","useTime":"2015-09-10 14:17:33","e_usage":"0.0599970581514709"},
{"name":"LED STAND","useTime":"2015-09-10 14:20:33","e_usage":"1.10919825898689"},
{"name":"LED STAND","useTime":"2015-09-10 14:23:33","e_usage":"1.9208018439918"}]
how to change this format to like this(for nvd3 line graph)?
function cumulativeTestData() {
return [
{
key: "LED STAND",
values: [ [ 2015-09-10 14:17:33 , 2.974623048543] ,
[ 2015-09-10 14:20:33 , 1.7740300785979]]
}
}
or theres easy way to make NVD3 line graph from mySql DB?
edit :
d3.json("./mysqljson/dbread.php", function(data) {
var dataLoad = d3.nest()
.key(function(d){return d.name})
.rollup(function(u){
return u.map(function(x){return [x.useTime,x.e_usage]})})
.entries(data);
nv.addGraph(function() {
var chart = nv.models.multiBarChart()
.x(function(d) {return d[0]})
.y(function(d) {return d[1]})
.margin({top: 50, bottom: 30, left: 40, right: 10});
chart.xAxis
.tickFormat(function(d) {
return d3.time.format('%x')(new Date(d))
});
d3.select('#mainExample')
.datum(dataLoad)
.transition().duration(500)
.call(chart);
nv.utils.windowResize(chart.update);
});
working code to use d3.json and d3.nest function

You can achieve that by using d3's d3.nest() method as follows:
Assuming your data structure as you received it using d3.json is data, then if you do:
x=d3.nest()
.key(function(d){return d.name})
.rollup(function(u){
return u.map(function(x){return [x.useTime,x.e_usage]})})
.entries(data);
Then the result would be:
{
key = "LED STAND"
values = [
["2015-09-10 14:17:33", "0.0599970581514709"],
["2015-09-10 14:20:33", "1.10919825898689"],
["2015-09-10 14:23:33", "1.9208018439918"]
]
}
I hope this helps.

Related

JSON for PHP + MYSQL error

My client sent me this JSON so I can loop and save the data in Mysql. I just can not get it because it's different from what I work at;
Can someone give me some hint and what is the difference from one format to another.
Error presented is: Warning: Invalid argument supplied for foreach () in line 28
foreach ($ json_data ['service_devices'] as $ key => $ value) {
Formator EX I've ever worked with:
{
"ordem_de_servico": [
{
"oser_numero_os": 23940493,
"oser_address_name": NAME;
CUSTOMER JSON
ordem_de_servico:
{
"oser_numero_os":23940493,
"oser_dt_abertura":"28/03/2018",
"servico":{
"serv_cod_servico":60,
"serv_descr_servico":"CORTE POR DEBITO"
},
"cliente":{
"clie_ident_cliente":638617,
"nome":"MARIA APARECIDA FERREIRA DO NASCIMENTO"
},
"unidade_consumidora":{
"unid_ident_uc":2436434,
"logr_nome_logr_expandido":"R JOSE GUIMARAES"
},
"faturas":[
{
"total_fatura":"88.44",
"ftcd_mes_ano_fatmto":"2017-04-01"
},
{
"total_fatura":"45.16",
"ftcd_mes_ano_fatmto":"2017-03-01"
}
]
}
My last attempt
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "webservice";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Read JSON file
$json = file_get_contents('oss.json');
//Decode JSON
$json_data = json_decode($json,true);
foreach($json_data['ordens_de_servico'] as $key => $value){
$os = $value["oser_numero_os"];
$data_abertura = $value["oser_dt_abertura"];
foreach($json_data['ordens_de_servico'][$key]['faturas'] as $index => $row){
$valorParcelas = $row["total_fatura"];
$sql = "SELECT numero_os FROM os WHERE numero_os = '$os'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "PULAR FATURA"."<p>";
}else {
$sql = "INSERT INTO faturas (valorParcelas, numero_os) VALUES ('$valorParcelas', '$os')";
if ($conn->query($sql) === TRUE) {
echo "<strong>".$valorParcelas." - FATURA OK"."</strong>"."<p>";
} else {
echo "Error Fatura";
}
}
}
$sql = "SELECT numero_os FROM os WHERE numero_os = '$os'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "PULAR"."<p>";
}
else{
$sql = "INSERT INTO os (numero_os, data_abertura) VALUES ('$os', '$data_abertura')";
if ($conn->query($sql) === TRUE) {
echo "<strong>".$os." - GRAVADO"."</strong>"."<p>";
} else {
echo "Error";
}
}
}
$conn->close();
?>
Change the line:
foreach($json_data['ordens_de_servico'] as $key => $value){
To:
foreach($json_data as $key => $value){
Since the new data doesn't have the outer element ordens_de_servico
Or you could edit the JSON file and add that element (don't forget to add the closing braces at the end as well.
Edit the first two lines of the file:
ordem_de_servico:
{
To:
{
"ordem_de_servico": [
And change the end of the file:
}
To:
]
}
Your JSON is incorrect. The main problem is json data itself which is not valid for json_encode() to generate PHP array.
First Possible solution:Remove ordem_de_servico: from our customer json and that will gonna work.
For json_decode(); method the json data must be valid and valid data is
{
"oser_numero_os":23940493,
"oser_dt_abertura":"28/03/2018",
"servico":{
"serv_cod_servico":60,
"serv_descr_servico":"CORTE POR DEBITO"
},
"cliente":{
"clie_ident_cliente":638617,
"nome":"MARIA APARECIDA FERREIRA DO NASCIMENTO"
},
"unidade_consumidora":{
"unid_ident_uc":2436434,
"logr_nome_logr_expandido":"R JOSE GUIMARAES"
},
"faturas":[
{
"total_fatura":"88.44",
"ftcd_mes_ano_fatmto":"2017-04-01"
},
{
"total_fatura":"45.16",
"ftcd_mes_ano_fatmto":"2017-03-01"
}
]
}
Second possible solution:What you can do is remove ordem_de_servico: string from your customer json data or make your json provider provide valid json data as follows with ordem_de_servico:.
{
"ordem_de_servico":{
"oser_numero_os":23940493,
"oser_dt_abertura":"28/03/2018",
"servico":{
"serv_cod_servico":60,
"serv_descr_servico":"CORTE POR DEBITO"
},
"cliente":{
"clie_ident_cliente":638617,
"nome":"MARIA APARECIDA FERREIRA DO NASCIMENTO"
},
"unidade_consumidora":{
"unid_ident_uc":2436434,
"logr_nome_logr_expandido":"R JOSE GUIMARAES"
},
"faturas":[
{
"total_fatura":"88.44",
"ftcd_mes_ano_fatmto":"2017-04-01"
},
{
"total_fatura":"45.16",
"ftcd_mes_ano_fatmto":"2017-03-01"
}
]
}
}
Look at the valid JSON format for json_decode() and there is not different types of json data only one type i.e. json.

Change JSON output "format" - PHP

(i'm a bit new in PHP / JSON) i have a PHP page that send me an array of informations to an Android application and i need to change the Json "format" so i can manage it in my Android application.
I tried adding the array to a PHP class but i only get errors.
From this (this is just an example):
[
{
"updated_at":"2012-03-02 21:06:01",
"fetched_at":"2012-03-02 21:28:37.728840",
"description":null,
"language":null,
"title":"JOHN",
"url":"http://rus.JOHN.JOHN/rss.php",
"icon_url":null,
"logo_url":null,
"id":"4f4791da203d0c2d76000035",
"modified":"2012-03-02 23:28:58.840076"
},
{
"updated_at":"2012-03-02 14:07:44",
"fetched_at":"2012-03-02 21:28:37.033108",
"description":null,
"language":null,
"title":"PETER",
"url":"http://PETER.PETER.lv/rss.php",
"icon_url":null,
"logo_url":null,
"id":"4f476f61203d0c2d89000253",
"modified":"2012-03-02 23:28:57.928001"
}
]
To this (other example):
{"master":[
{
"updated_at":"2012-03-02 21:06:01",
"fetched_at":"2012-03-02 21:28:37.728840",
"description":null,
"language":null,
"title":"JOHN",
"url":"http://rus.JOHN.JOHN/rss.php",
"icon_url":null,
"logo_url":null,
"id":"4f4791da203d0c2d76000035",
"modified":"2012-03-02 23:28:58.840076"
},
{
"updated_at":"2012-03-02 14:07:44",
"fetched_at":"2012-03-02 21:28:37.033108",
"description":null,
"language":null,
"title":"PETER",
"url":"http://PETER.PETER.lv/rss.php",
"icon_url":null,
"logo_url":null,
"id":"4f476f61203d0c2d89000253",
"modified":"2012-03-02 23:28:57.928001"
}
]
}
My PHP page that create the JSON array:
<?php
class card{
public $id = 0;
public $name = "";
public $value = 0;
public $imgpath = "";
public $rarity = "";
public $litness = 0;
public $dankness = 0;
public $expansion = "";
}
$b= array();
$connessione = mysqli_connect("", "", "", "");
$query = "insert_query_here";
$risultato = mysqli_query($connessione, $query);
while($row = mysqli_fetch_assoc($risultato)){
$card = new card();
$card->id = $row['id_card'];
$card->name = $row['name'];
$card->value = $row['value'];
$card->imgpath = $row['imgpath'];
$card->rarity = $row['name_rarity'];
$card->litness = $row['litness'];
$card->dankness = $row['dankness'];
$card->expansion = $row['expansion_name'];
$b[] = $card;
}
$out = array_values($b);
print json_encode($out);
Try the following:
$out = ['master' => array_values($b)];
print json_encode($out);
This will add the key master in the main array, and the rest will be nested in it.

How to insert array values in mysql with a loop

Reading a Textarea with jquery , splitting each line in Array then with ajax posting that array in mysql through php but in results only first value inserted.
Table:
CREATE TABLE IF NOT EXISTS addresses (
id int(8) NOT NULL PRIMARY KEY,
user_id int(8) DEFAULT NULL,
address_value varchar(100) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
Here is Jquery Code :
$('#insertad').click(function(){
var lines = $('#txtArea').val().split('\n');
var phparray = new Object();
for(var i = 0;i < lines.length;i++){
phparray[i] = lines[i]; //store value in object
}
$.post('functions.php?action=insertad', {array1:$.param(phparray)}, function(resp){
$('.text-success').html(resp);
if(resp == 'Added'){
$('.text-success').html('Added Address :');
}
});
});
Here is PHP Code :
if ($action == 'insertad') {
$pieces = explode('&', $_POST['array1']); //explode passed serialized object
$phparray = array();
foreach ($pieces as $piece) {
list($key, $value) = explode('=', $piece);
$phparray[$key] = $value; //make php array
}
$length = count($phparray);
for ($i = 0; $i < 7; $i++) {
$sql = "select address_value from addresses where address_value = '$phparray[$i]'";
$qry = mysql_query($sql);
$numrows = mysql_num_rows($qry);
if ($numrows > 0) {
echo "One Found !!" ;
} else {
$sql = "insert into addresses (address_value) values ('$phparray[$i]')";
$qry = mysql_query($sql);
if ($qry) {
echo "Added";
}
}
}
}
Try this please...
JS:
var $textarea = $('textarea'); // maybe you have to specific your selector!
var textArray = $textarea.val().split("\n"); // this array is already done, your have not todo next for() loop
$.post('functions.php', {
action: 'insertad',
array1: textArray
}, function(results) {
$.each(results, function(reslt) {
if(result === 'Added') {
$('.status').append(result);
}
else {
$('.status').append(result);
}
});
});
PHP:
if($action === 'insertad') {
$results = [];
$input = $_POST['array1'];
foreach($input AS $textLine) {
$escapedTextLine = mysqli_real_escape_string($resource, $textLine);
$result = mysqli_query($resource, 'select address_value from addresses where address_value = "'.$escapedTextLine.'"');
$affectedRows = mysqli_num_rows($result);
if($affectedRows > 0) {
$results[] = 'One Found !!';
}
else {
$result = mysqli_query($resource, 'INSERT INTO `adresses` (`address_value`) VALUES("'.$escapedTextLine .'");
if($result) {
results[] = 'Added!';
}
}
}
return $results; // we return all done results to check this array in ajax response
}
Notice: I wrote the code blind, so maybe you have to make some small changes for e.g. your variables or something like that.
Notice 2: I write the code with mysqli, so you have to rewrite your Database connection setup code.
Please never forget to use mysqli_real_escape_string do something with user contents.

Passing php file to json fail to load data

I have tried to add a php file as the source of data for a jquery calendar that uses json as below:
<script>
$(document).ready(function() {
$("#eventCalendarHumanDate").eventCalendar({
eventsjson: 'modules/events/json/event.humanDate.json.php',
jsonDateFormat: 'human'
});
});
</script>
The php file works when i echo variables only but when i connected to the database and looped, it fails and i get the error "error getting json" But running my code separately i get no error from the php file itself.
<?php
$hostname_app_conn = "localhost";
$database_app_conn = "xx";
$username_app_conn = "xx";
$password_app_conn = "";
$app_conn = mysql_pconnect($hostname_app_conn, $username_app_conn, $password_app_conn) or trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_app_conn, $app_conn );
$query_rs_content = "SELECT * FROM `mod_events_events` WHERE `active`=1 ORDER BY `Id` LIMIT 365";
$rs_content = mysql_query($query_rs_content, $app_conn) or die(mysql_error());
$totalRows_rs_content = mysql_num_rows($rs_content);
header('Content-type: text/json');
echo '[';
$separator = "";
$days = 16;
$i = 1;
echo $separator;
while($row_rs_content = mysql_fetch_assoc($rs_content))
{
echo ' { "date": "'.$row_rs_content['eventday'].'", "type": "'.$row_rs_content['type'].'", "title": "'.$row_rs_content['Title'].'", "description": "'.$row_rs_content['teasertext'].'", "url": "" },';
}
$separator = ",";
echo ']';
?>
thanks in advance.
You should use the json_encode() function, something like this:
//more code above
$array = new array();
while($row_rs_content = mysql_fetch_assoc($rs_content))
{
$array[] = array(
'date' => $row_rs_content['eventday'],
'type' => $row_rs_content['type'],
'title' => $row_rs_content['Title'],
'description' => $row_rs_content['teasertext'],
'url' => '',
);
}
header('Content-type: application/json');
echo json_encode($array);
die();
Most likely you had some character not being escaped properly or something else that was causing it not to be a valid json array so Javascript is dying trying to parse it.

PHP get the results of a function into another

I have this function
function getTwitterAuth($user_id) {
$d = "SELECT * FROM `twitterAccounts` WHERE `user_id`='".$user_id."'";
$dr=mysql_query($d) or die("Error selecting twitter account: ".mysql_error());
$drow = mysql_fetch_assoc($dr);
**$twitter_auth_token** = $drow['oauth_token'];
**$twitter_auth_secret** = $drow['oauth_token_secret']
}
It will tell me the result of two variables that I will need to pass then to this other function:
function twitterReply($twitter_message, $reply_to_id) {
$twitterObj->setToken(**$twitter_auth_token**, **$twitter_auth_secret**);
$twitter_user = $twitterObj->get_accountVerify_credentials();
try{
$twitter_user->id;
$twitterObj->post_statusesUpdate(array("status" => $message, "in_reply_to_status_id" => $reply_to_id);
//echo "done";
}
catch(EpiTwitterException $e){}
}
How do I do it??
Thank you very much
function getTwitterAuth($user_id) {
$d = "SELECT * FROM `twitterAccounts` WHERE `user_id`='".$user_id."'";
$dr=mysql_query($d) or die("Error selecting twitter account: ".mysql_error());
$drow = mysql_fetch_assoc($dr);
$twitter_auth_token = $drow['oauth_token'];
$twitter_auth_secret = $drow['oauth_token_secret'];
return Array("token" => $twitter_auth_token, "secret" => $twitter_auth_secret);
}
function twitterReply($twitter_auth_token, $twitter_auth_secret, $twitter_message, $reply_to_id) {
$twitterObj->setToken($twitter_auth_token, $twitter_auth_secret);
$twitter_user = $twitterObj->get_accountVerify_credentials();
try{
$twitter_user->id;
$twitterObj->post_statusesUpdate(array("status" => $message, "in_reply_to_status_id" => $reply_to_id);
//echo "done";
}
catch(EpiTwitterException $e){}
}
$res = getTwitterAuth($user_id);
twitterReply($res["token"], $res["secret"], $twitter_message, $reply_to_id);
Edit: As seen in another answer setting the $twitter_auth_token and $twitter_auth_secret is redundant the last three lines of the function getTwitterAuth could be appended to:
return Array("token" => $drow['oauth_token'], "secret" => $drow['oauth_token_secret']);
function getTwitterAuth($user_id) {
$d = "SELECT * FROM `twitterAccounts` WHERE `user_id`='".$user_id."'";
$dr=mysql_query($d) or die("Error selecting twitter account: ".mysql_error());
$drow = mysql_fetch_assoc($dr);
$array = array();
$array['twitter_auth_token'] = $drow['oauth_token'];
$array['twitter_auth_secret'] = $drow['oauth_token_secret'];
return $array
}
$twitterTokens = getTwitterAuth($user_id);
Now you can access those values using $twitterTokens['twitter_auth_token'] and $twitterTokens['twitter_auth_secret']
AS the above peope have said,
function getTwitterAuth($user_id) {
....
**$twitter['auth_token']** = $drow['oauth_token'];
**$twitter['auth_secret']** = $drow['oauth_token_secret'];
return($twitter);
}
function twitterReply($twitter,$twitter_message, $reply_to_id) {
$twitterObj->setToken(**$twitter['auth_token']**, **$twitter['auth_secret']**);
...
}
$twitter_info = getTwitterAuth($user_id);
twitterReply($twitter_info, $twitter_message, $reply_to_id)

Categories