I have a table called flagged_posts with the following rows:
id
thought_id (id of the post being flagged)
user_id (id of the user who is flagging the post)
I am trying to implement a graph which (for now) will show how many flagged posts have occured ed for the current date (x-axis will show days, i.e. monday, tuesday etc, y-xis will show number of incidents).
I have seen charts.js but, I am unsure whether these charts can be used based on database data. I.e. if monday has 10 flagged incidents, $mon_flagged = 10, then use the variable to display data in the graph? or in another way which automatically gets data from db?
https://www.amcharts.com/tutorials/using-php-to-hook-up-charts-to-mysql-data-base/You first need to build your data into an array that will be in a useful format for the chart library.
After you have selected the relevant data, format it into an array something like this:
function formatDataForChartsJs($result){
while ( $row = mysql_fetch_assoc( $result ) ) {
if($row['post_is_flagged']) {
$data[$row['date_created']] += 1;
}
}
return $data
}
Then you should end up with an array suitable for use with your javascript charting library. Something like this:
$data = [
2016-03-7 => 10
2016-03-08 => 15
...
]
You then need to understand how you will pass the data to front end so that you can use your data with a javascript chart library.
The normal way to do this it to take your php data variable and encode it as a json string.
$data = fetchData();
$formattedData = formatDataForChartsJs();
$dataAsJsonString = json_encode($formattedData);
Then in your view:
<script type=text/javascript>
var graphData = <?php echo $dataAsJsonString ?>
//use your graph data variable with chart.js or other javascript graph library
</script>
There is a good tutorial here, but I would advise using json_encode rather than their approach to printing a JSON string.
https://www.amcharts.com/tutorials/using-php-to-hook-up-charts-to-mysql-data-base/
Related
I am working with some integrations. I get data in Javascript file and I need to change the format slightly.
The data is received by Javascript in the following format:
["{label=Created By ID, value=Contact_ID__r.CreatedById}",
"{label=Created Date, value=Contact_ID__r.CreatedDate}",
...]
I need to convert the data in the following format in order to pass it ahead:
[{"label":"Start Date","value":"Contract_Start_Date__c"},
{"label":"Created Date", "value":"Contact_ID__r.CreatedDate"},
...]
I tried using JSON.stringify() and .replace() in various combinations to change the format. Eg: data[i].replace(/"/g, ''). Nothing worked. I am not able to change the format.
Please help. Thank You!
More Info:
The data is received from apex(just like java) in the form of Map<Map<String,String>,String>.
Eg:["{label=Created By ID, value=Contact_ID__r.CreatedById}","account"}]
In javascript, I extracted Map<String,String> part of it as follows:
//result.data contains the data returned by apex method.
//Variable availableOptionsForAccountFields will be used to display the data.
var iterator = 0;
var keys = Object.keys(result.data); //store the keys.
Object.keys(result.data).forEach(fieldToBeAddedAsAvailableOption => { //loop over the returned data.
//Identify the object of the field and add it to respective variable so that it can be displayed to the user
if (result.data[keys[iterator]] == 'account') {
this.availableOptionsForAccountFields.push(fieldToBeAddedAsAvailableOption);
}
iterator = iterator+1;
});
//After execution of this loop, the variable availableOptionsForAccountFields will have all the values to be displayed in dual listbox.
After extracting the data, I am left with the following data:
["{label=Created By ID, value=Contact_ID__r.CreatedById}"]
I need to convert this data into the following format so that I can display it using HTML:
[{"label":"Start Date", "value":"Contract_Start_Date__c"}]
I am working with following APIs:
http://api.steampowered.com/ISteamApps/GetAppList/v0002/?format=json
https://store.steampowered.com/api/appdetails?appids=GAMEID
(gameid example: "730" - counter strike)
My goal with both of these is to search them for data. For example I want the first API to give me a name of a game based on it's ID and the second one to give me specific information about a game for example if it has trading cards (id:29 in the API).
I tried a few things but I am kinda lost on this beacuse I don't really understand JSON so I would really appreciate some help.
I am open to both PHP and JS solutions.
IN PHP, you can use the json_decode() function to convert JSON data into an array. You can them access the values as you do for a classic array :
$appID = 730 ;
$url = 'https://store.steampowered.com/api/appdetails?appids=' . $appID ;
$content = file_get_contents($url) ; // retrieve the JSON data string from the website
$data = json_decode($content, true); // convert the JSON string into PHP array
echo $data[$appID]['data']['name'] ; // Counter-Strike: Global Offensive
var_dump($data[$appID]['data']['is_free']); // bool(true)
I've looked around, but haven't been able to find a clear way of returning Laravel timestamps / datetimes in a particular format. It doesn't really matter to me how it's saved in the database, but when I'm pulling the data, I'd like to format it so that it can be parsed by JavaScript. Does someone know of a good way that doesn't involve having to create multiple accessors?
Edit: To add more detail, I'm actually using AngularJS and would like the date returned in a format so that it can be understood by Angular and its date filter. With the current format, the date filter doesn't work because it can't parse the date, from what I can tell.
To define an accessor, create a getFooAttribute method on your model where Foo is the "camel" cased name of the column you wish to access.
So, you should define an accessor for the test_date (or anything else) attribute. The accessor will automatically be called by Eloquent when attempting to retrieve the value of test_date.
(In the example I'll define it in the User model)
<?php
namespace App;
use Carbon\Carbon;
class User extends Model {
protected $table = 'users';
public function getTestDateAttribute($date) {
//What format do you store in db?
$storedformat = createFromFormat('Y-m-d H:i:s', $date);
//What format would you like to show?
$customformat = $storedformat->format('Y.m.d. H:i:s');
return $customformat;
}
}
Then you'll see the following format by default:
$user = User::find(1);
$user->test_date; //2015.11.12. 8:50:20
If you'd like to write simplier code, you should use Traits.
Let's define the DateTrait in App\DateTrait.php file:
<?php
trait DateTrait {
public function getTestDateAttribute($date) {
//What format do you store in db?
$storedformat = createFromFormat('Y-m-d H:i:s', $date);
//What format would you like to show?
$customformat = $storedformat->format('Y.m.d. H:i:s');
return $customformat;
}
}
Then use it every model where you'd like to format the test_date column.
<?php
namespace App;
use Carbon\Carbon;
class User extends Model {
use App\DateTrait;
...
}
In your view just do something like this:
$variable->created_at->format('m-d-y')
This page here may be useful for getting familiar with Carbon dates and how you can use and format them.
Regarding the parsing of them to a format Javascript can interpret, perhaps you could do something like this - assuming it is coming from an eloquent object you have pulled in to a view or something like that:
{{ (new Carbon\Carbon($dataPassedIn->created_at))->format('F d, Y H:ia') }}
Which would return a date like this September 02, 2015 09:43am, although I'm not sure of the exact format you would need for parsing in to javascript.
I'm working with Laravel 4 to build an applicaton.
Now, I do count all my visitors in a 'unique' way. So the system does chack if there was already a visit this day and if so, it just counts a click in the database.
What my database structure look like:
I want the system to count the visitors (so the IP adressess) of day X in month X. Like the visitors of 30/04/2015 wich is in my table 2015-04-30. I want to count all the IP adressess of that day and the other days of a month. But when the month is over, it needs to get the values of the next month, so I want the values of the current month.
The hits are just to count the 'clicks' on my site, so don't need to mention that.
The date and visit_date give me the current date of visiting and visit_time gives me the time of the visit.
My current code looks like this to display the values:
public function index()
{
$select_stats = DB::table('visitor')->whereBetween('visit_date', array(date('Y-m-01'), date('Y-m-t')))->get();
$month = date('m');
$get_count = DB::select(DB::raw("SELECT count(*) FROM visitor WHERE MONTH(date) = $month GROUP BY DAY(date)"));
foreach($select_stats as $statics) {
//change our object to an array
$statics = array();
}
return View::make('admin.home.index')->with('stats', $select_stats)/*->with('count', $get_count)*/;
}
But When I try to display this code, with the counted numbers, it doesn't work anymore. My view looks like this:
<script type="text/javascript">
var visitors = [
#foreach($stats as $stat)
['{{ date("d/m/Y", strtotime($stat->date)) }}', 55],
#endforeach
];
</script>
So the 55 inside of my view are the counted visitors as output.
Could someone help me as soon as possible please?
Kindest regards,
Robin
I'm not really understanding all that well, but a few things that could help... 1. I'd really suggest looking into using model classes in stead of using DB raw queries. Thats where Laravel is really great. For example it would be:
$select_stats= Visitor::where('visit_date', '>=', Carbon::now()->startOfMonth())->get();
$get_count = $select_stats->count();
In stead of doing a foreach in the script, I'd return a json array. So you could send the 'stats' variable to your view instead as:
with('stats', $select_stats->lists('visit_date'))
and then in the script you'd just have to use:
{{ json_encode($stats) }}
Let me start by explaining the situation:
I have a MySql table that contains several columns, of which a user id, a race id, a lap time, a lap number and I want to put this information into an array in PHP which I will then send to a java script.
My JavaScript array should end up looking like this :
first row:
[laptime1 user1, laptime2 user1, laptime3 user1,...]
second row:
[laptime1 user2, laptime2 user2, laptime3 user2,...]
Here's my current situation:
I first tried to test this situation for a single user and ran into lots of problems because my lap times in MySql are floats and when using json_encode it turned everything into strings, which did not work for my javascript as it started outputting the wrong values.
For example:
The first value was "8" instead of "84,521", then the second value was "4", etc..)...
Sadly, I found a potential solution with the numeric check option, but cannot use it as my hosting runs a PHP version that doesn't support it.
So I found the following solution, which I fiddled with a bit and that works for a single user (it might look messy to you, I'm really a beginner and punching above my weight, but it works) :
$query = doquery("SELECT racelaptime,userid FROM {{table}} WHERE raceid='1' ORDER BY racelap", "liverace");
while(($result = mysql_fetch_array($query))) {
$data[] = (float)$result['racelaptime'];
}
$script = $script . "\nvar myArray = new Array(";
foreach ($data as $key => $value){
if ($key < (count($data)-1)){
$script = $script . $value . ',';
}
else {
$script = $script . $value . ");\n";
}
}
This outputs an array in JavaScript that looks like this :
myArray=[84.521,83.800,81.900]
Which is great, as this is exactly what my java script requires as input (time in seconds, separated by commas for each lap).
Now I would like to implement the multiple user element but I'm stumped as to how I can work that out...
My MySQL query is still sorted by race lap but I also kind of need to sort the data by user id as I want all the laps of each user sorted in 1 row, Also, the user id is unknown to me and can vary (depends which user posts the time) so I can't really do a "if userid==1 save this here and then go to next one".
Should I use a foreach statement in the while loop that stores the data, but how can I tell him to store all the laps by the same user in the first row (and the next user in the second row, etc...) without using tons of SQL queries ?
If you can offer a more elegant solution than my current one for passing the PHP array to JavaScript, I would be more than happy to make changes but otherwise a simple solution using the current "setup" would be great too (hope it's all clear enough).
Any help would be very much appreciated, thanks in advance !
For multiple user element I would use a multidimensional array >
$query = doquery("SELECT racelaptime,userid FROM {{table}} WHERE raceid='1' ORDER BY racelap", "liverace");
// Loop the DB result
while(($result = mysql_fetch_array($query))) {
// Check if this ID is already in the data array
if(!array_key_exists($result['userid'], $data)){
// Create array for current user
$data[$result['userid']] = array();
}
// Add the current race time to the array (do not need to use the float)
$data[$result['userid']][] = $result['racelaptime'];
}
// Echo json data
echo json_encode($data);
Now what you need to do on the Javascript side when handling this array is to go through each of the user
$.each(data, function(key, value){
// Use parseFloat to keep the decimal value
alert(key + ' Has the following values - ' + value);
// If you want to display the racing values you simply
$.each(value, function(k, parseFloat(v)){
alert(v);
})
})
Is this what you needed or am I completely out of the scope?