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) }}
Related
Question is about best way to handle data.
Let's assume we have such key -> value data:
"user#gmail.com": { "name": "John",
"age": 20,
"job": "developer",
"favourite_food": ['taco', 'steak']
//...etc
}
//...etc
There is a lot of data for users with key "email", like a million.
And usually I had to search users by their email.
But today my boss came up to me and said he want to search users by their names and of course keep possibility to search by email. On the other day he said he want my program to realize search by age and so on.
My first thought was to iterate over data with, for example, this php code:
foreach($email as $data){
foreach($data as $k => $v){
if($v == 'search value'){
return $email;
}
}
}
But this solution is not good for big amount of data.
My second idea was to iterate over first data and create for each email own table to make it look like this:
$a = "user#gmail.com": {//all data}
$b = "John" : {//all data including email}
$c = "developer":{//all other data}
// and so on
But my users getting older with time, so I have to update user age every time the data in my main object changes.
So, my question is, what is the best way to implement such logic using any programming language?
Some notes:
It had to be done by using programming language without touching MySQL or any other DB.
I think using the year of birth of users instead of age might be better in this situation.
You can use index if you are using database.
If not, I think you can create index by yourself.
A simple index strategy is:
Do not change the original data, but add index dicts where the keys are index and values are email.
Like in python you can add two indices, name and yearofbirth:
name = {"John": ["xx#xx.com", "cc#cc.com", "aa#c.com"],
"Mike": ["aa#aa.com", ...],
#...etc}
yearofbirth = {"1981":["xx#xx.com", "cc#cc.com"],
#...etc}
In this way, you can search by name or yearofbirth to get the email and then fetch the original data.
And it is fast.
I am in the middle of making a scheduling program that will be displayed on a bigger touchscreen TV. I have an array call date[] that just contains the date of every friday for the year since our company refers to weeks by their fridays, and that's how it is in the database I'm pulling from. I'm using moment.js:
var date = [];
var newDate;
for (var x = 0; x < 52; x++) {
newDate = moment().startOf('year').day('friday').add(x, "weeks").add(when, "years");
newDate = moment(newDate).format('MM-DD-YYYY');
date.push(newDate);
then I have three columns of a local database being pulled out and being pushed into a multidimensional array in php
foreach ($conn->query($sql) as $row) {
array_push($jobNo, $row['JobNumber']);
array_push($jobState, $row['JobState']);
$dform = new DateTime($row['WeekDate']);
$dform = $dform->format('m-d-y');
array_push($jobDate, strval($dform));
}
and then I'm transferring it into a javascript array:
<?php $data = getData(); ?>
<script type="text/javascript">
var data = <?php json_encode(print_r($data)); ?> ;
</script>
getData() is the php function I'm using to pull the data from the database.
I have a grid of draggable squares with each of the dates of the fridays on them and I'm dragging them to a drop panel and saving the date in a selection[] array.
But, now I'm about to just take the dates selected and use a table view on another page where I will be showing the data of just the selected dates. Is there anyway for me to maybe take it another step deeper and relate the date array to the data array? or is it possible to sort the data array by the date and just keep everything else with the job number and state?
I'm fairly new to making something this in depth so any help is welcome. Thank you very much in advance.
EDIT: What I want to be able to be able to use the date to call all the job numbers and job states that might be connected to that date.
pretty much like
foreach(date[] as day){
for (var i = 0; i < data.length; i++){
if (date == data[1][i])
//but right here I'm not sure where to go or what to do
//I would like to just be able to call data[05-19-17] and
//use that to list the job numbers and job states related to
// that date.
}
}
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/
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?
EDIT 4/16/2012: I solved the issue of getting the timezone abbreviated into a letter format, had to download a third party sorting method and add a few things to get the desired results. The only problem now is Daylight Savings Time handlers, but there are a bunch of subjects on that. However if anyone knows how to handle UTC Daylight Savings hanlers, please feel free to help.
Thank you everyone.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
I've made an html table that I've binded with a javscript viewmodel using knockoutjs that pulls the info from a private server usin JSON function. I'm trying to make each column sortable (click on the column header once to get everything in descending order according to that column's info; click header again to get everything in ascending, and a third time to get everything in it's original order).
PLEASE NOTE: I have searched for my problem and have seen other solutions, but nothing so far has worked for me. I'm hoping to find a solution specific towards my code.
The Javascript ViewModel.js file is basically like this:
Event(column1, column2, ...., columnN){
var self = this;
self.column1 = column1;
self.column2 = column2;
.
.
}
//Sort column2 that has the Dates (dd (day) HHMM (hours/minutes) mmm (month) yy (year) format)
self.sortColumn = "Column2"
self.sortAscending = true;
self.SortByDates = function(){
if(self.sortColumn == "Column2")
self.sortAscending = !self.sortAscending;
else{
self.sortColumn = "Column2"
self.sortAscending = true;
}
self.rows.sort(function(a,b){
if(self.sortAscending == true)
for(self.Column2 in self.rows)
return a.Column2 > b.Column2 ? 1 : a.Column2 < b.Column2 ? -1 : 0;
else
return a.Column2 < b.Column2 ? 1 : a.Column2 > b.Column2 ? -1 : 0;
});
}
//specify location of server and info and get them
function getEvents(){
$.getJSON("http://.........",
function (data){
$.each(data.d, function(i, item){
handleEvent(item)
})
}
);
}
//pushes (AKA populates) info from server into the table
function handleEvent(item){
var newEvent = new Event(item.Column1InfoFromServer,
formatJSONDate(item.Column2DateInfoFromServer), .....)
this.Model.rows.push(newEvent);
}
//Formats the date info from server into dd (day) HHMM (hours/minutes) mmm (month) yy (year)
formatJSONDate(jsonDate){
var date = new Date(parseInt(jsonDate.substr(6)));
return date.format("dd HHMM mmm yy");
}
this.Model = new ViewModel();
this.getEvents();
ko.applyBindings(this.Model);
I'm having one hell of a hard time getting the Date in its converted form (yes it HAS to be in that form --> actually, I still need to figure out how to include the time-zone abbreviation right after the 'HHMM' part based off of UTC). So lets say I have "11 1136 Apr 12" and "22 1624 Jan 12" among other dates in the table. Right now when I try sorting the table according to the dates, they don't sort appropriately. Any help is appreciated, thank you.
EDIT: To be clear, I'm trying to display the timezones in military timezone codes (timezones 'A'-'Z'). Also, the dates being taken from the server are already in UTC.
UPDATE:
I was looking at another question, and someone created a knockout grid addon:
https://github.com/ericmbarnard/KoGrid
I bet this might help you out :-)
---OLD ANSWER for nostalgia----
There are some great helper functions in the Underscore library, one of them being sort:
http://documentcloud.github.com/underscore/#sortBy
sortBy_.sortBy(list, iterator, [context]) Returns a sorted copy of
list, ranked in ascending order by the results of running each value
through iterator. Iterator may also be the string name of the property
to sort by (eg. length).
_.sortBy([1, 2, 3, 4, 5, 6], function(num){ return Math.sin(num); });
=> [5, 4, 6, 3, 1, 2]
I'd give this a shot, along with creating a better model for your dates. It sounds like you need to store a property which is a unique point in time, along with a text value for the user.
Well, to get numeric values for your date objects, sort by pDate.valueOf(). This will give you the # of millisecond since epoch.
However, there is an issue inside of your sort function, but I'm not sure what it is supposed to do. You can't walk an object inside of a sort function and return values like that.