How to properly handle a car race in MySQL? [closed] - php

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
most likely a clueless question but I would like to start off on the good foot:
Despite trying my best, I have actually never really learned to program and I'm kind of "learning as I go" so please excuse me if this seems very obvious to you...
It's more of a suggestion and feedback kind of question rather than pure programming.
My situation is the following:
I'm building a racing game that would receive various inputs from a number of users (through a php website), I am storing that information in a MySQL database, and once a week I would like to process all that information to generate "lap times", which will then create a race (my "output").
Not taking into account the various methods of calculating that output, I need to do two important things which I'm not sure how to begin with at all :
1) Storing the race information for every user (lap time per lap, fastest lap, race position per lap, race position at end of race, award points depending on the position).
Where and how should I optimally store those informations ?
I have created a race DB with a unique identifier that auto increments, I'm thinking I will generate 1 set of data for each race, so should I store all the information pertaining to that race in there ?
Would I then create a data row (with type time?) for the lap time informations (1 row for lap1, 1 row for fastest, etc... ?)? But how would I know which user (I have a unique userID for each) did which lap (how would I assign the userID to the lap time)?
2) At the end of the race I need to award points depending on race position at the end, should I just compare total lap times (additional row?) and sort by lowest first ? The points data would be stored in the user DB ?
I appreciate any input you might have for the modeling of this project !

Drop every lap_round, lap_time and position in the DB and add a user_id and a race_id.
Afterwards query the laps. That way you can tell which is fastest overall, fastest per user, time per lap and much more.
To get the position query the db for the last lap. It holds its position.
Points are user based, so put them in the user table. Just add. But if you want to tell how many points were added per race than make a seperate table points (user_id, race_id, points)

Related

mysql table design, not sure on best approach [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I am building a mysql database to store golf scores.
I am not sure on the best approach to store the round information.
Each round is made up of either 9 or 18 holes and for each hole I need to store
Hole id
Number of shots
Stableford points
Green in regulation
Fairway hit
Number of putts
Number of penalty shots
My question is should I have one huge table, that stores all of this. Like a rounds table. and have the above 7 fields 18 times for each hole.
Or should I have a smaller rounds table that just contains the date played etc and then another table such as scores that just has the 7 fields, and have multiple rows in that table to make up the complete round?
I guess I am asking in terms of which would perform better and which is the better design?
Thanks
Definitely two tables. First, let's name it rounds will contain data relevant to round itself, such as date, id of the golf terrain etc. The other, let's name it hole, will have 7 aforementioned fields, together with round_id field that will reference round that particular hole belongs to.
Main benefits are clearer design and avoidance of redundant data. If you keep everything in one huge table, each row would need to contain not just fields relevant to the single hole, but also fields relevant to the whole round (date, id of the terrain..) -> same data in many rows, unnecessary. What if you mistakenly enter wrong date? You would have to change it in all 9 to 18 rows instead of only one.
See also:
Normalization in MySQL
Database normalization
Divide your information as much as possible. Otherwise you'll face alot of redundant data.

How to return database results in a fair manner - MySQL , PHP [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I'm creating a function that retrieves records based on several different fields and then stores those records so we can query them later.
When querying the records, we're selecting a record to be used elsewhere if it matches the requirements of another set of fields/criteria.
For example:
Returning employee records so that one of them can be selected for a new position (management maybe?) based on fields such as skill set, location, and so on...
The problem
Say I loop through these stored records (in an array or something similar) and I check if the first employee in the array is suitable for the position, then find out they are, so then add them to the position, I'm neglecting the other x amount of employees that have been stored. I feel like this would be an issue because it might turn out that the order in which someone is stored might determine the likelyhood they are chosen for the position.
I thought this might be solved by creating a sorting function to sort the stored records based on the employers preferences (location, salary, availability,...), although I'm not sure how to implement this.
I'm wondering if there is any built in MySQL functions that would help sort the records based on something?
This might be something I might have to figure out on my own, but I thought I'd ask just in case there was anything useful I could use.
I hope the question was clear. If not, please comment below.
Just thinking out loud - won't sorting create the same issue you are trying to avoid - unless you can come up with a weighted score...
create table as employees_to_consider as
select e.*,
availability_score*availablity_factor
+ salary_score*salary_factor
+ location_score*location_factor as weighted_score
from employees e
where -- whatever your criteria is for selection here
order by weighted_score
The real task is deciding how to determine the score for each factor and what the appropriate weight should be.
For example, salary score can be determined by taking the ratio of what the employee is willing to work for by the target. If they match, it can be scored as 50. The number can be increased by the amount the employee is willing to work under the target and decreased by an amount they are over. Salary is pretty important so the factor might be 33%.
Similarly, if the employee lives with 15 minutes, then they can be scored at 75, within 30 at 50, over 30 25. Location is not as important as salary so it is scored at 10%.
Hopefully, you will be able to assign meaningful scores and factors to each measure.

User bandwidth quota management with mysql php [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have a large user table in mysql with 50k+ entries.
these users have limited download quota for their stored files in my website.
currently the quota resets every 24 hours by resetting the traffic count in a seperate 'traffics' table (where each row has a userid and a trafficused field entry)
so that makes two tables with 50k entries each (representing 50k users)
this system is working fine so far, but I have no way of keeping a user's bandwidth usage history since to reset the quota per day, I have to clear the traffics table.
I use php to update transferred bandwidth on each download completion.
I need to be able to limit quota per day and/or per month as efficiently as possible without making a mess out of the mysql tables.
There is another complication, I have seperate user quotas for different filetypes. for example .iso files have no quota, .mp4 files have 5gb per day limit. and .rar files have 10gb per day limit.
and maximum user quota per day is 20gb.
I know it all sounds very confusing. I can post the table structures here if needed.
Please try to help if you can.
Thanks
50k rows is a medium-size table, not large. Don't fear that size, just index it correctly.
Try adding a DATE column to your traffics table. Once a day run a MySQL event to do this query:
DELETE FROM traffics WHERE trafficdate < CURDATE() - INTERVAL 30 DAY
This will purge old traffic records.
When you need to know today's usage do
SELECT trafficused FROM traffics WHERE userid = whatever
AND traFficdate = CURDATE()
Similarly, when you need 30 days' worth of traffic, do
SELECT SUM(trafficused) FROM traffics WHERE userid = whatever
To store a traffic transaction, do this
INSERT INTO traffics (userid, trafficdate, trafficused)
VALUES (whatever, CURDATE(), filesize)
ON DUPLICATE KEY UPDATE trafficused=trafficused+filesize
Make sure your traffics table has the composite primary key (userid,trafficdate).
Also create the compound index (userid,trafficdate,traffics) to make your queries faster.
This approach, with ON DUPLICATE KEY, means you don't have to have a row for every user for every day.
Handling separate bandwidth per file type is a question of adding a filetype column and putting it into the indexes and queries.

Strategy for finding active/inactive users in a period of time [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I need to implement a mechanism with the following abilities:
Add new users
Delete a user
Enable a user
Disable a user
And also let the administrator to select a period of time and then show which users were:
Available in the system at that period
Enabled
Disabled
The result should be for that exact period of time.
Note: A user might be enabled or disabled several times and I need to keep track of every single change. So, if the user is disabled between the March 1th and April 2nd, it should not be appear in the results if the administrator querying a time period between March 1th up to April 2nd, but it should be included in the results if the administrator querying any other period of time.
Also the tricky part is to contain the usesr who has been added, deleted, enabled or disabled before the period that administrator querying.
I don't have any set up for now, so I'm pretty up for any idea. Actually I'm thinking of a mechanism like a log which you can query that later, but it should be really fast because I need to use it in many places.
Also I prefer to do everything in a single MySQL Query, however the PHP combination/interaction is also okay.
Per commentary, look into Slowly Changing Dimensions:
http://en.wikipedia.org/wiki/Slowly_changing_dimension
An additional top, having implemented this a few times myself. Personally, I've found it better to have two sets of tables, rather than a single one.
Think of the main one as a normal table with an extra rev (for revision_id) field:
id, rev, field1, field2
rev is a foreign key to the revisions table:
id, rev, field1, field2, start_date, end_date
And if you ever use Postgres to implement it, I'd advise to look into the tsrange type instead of two separate start_date and end_date types.
The main table vs history tables makes "normal" queries perform better and much easier to index.

Possible ways to create a turn based system using PHP/MySQL [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 11 years ago.
Improve this question
Right, I'm trying to create a system where by the user can do something, but then must wait until all the other users in the mysql table have made their move, i.e
User1 makes move, user2 and 3 must wait
user2 makes move, user 1 and 3 must wait
user3 makes move, user 1 and 2 must wait
user1 makes move...
One way I thought of was to give each of the users an number (ranging from 1 to the total number of players, say 6) and then when a player makes a move, set their number to the max number (6) and decrease everyone else's number by one, so the one with the minimum number is the only one who can play.
That's my only idea, is there an easier or alternative way?
My suggestion would be just store the last move date as a datetime. When you need to check if a user can move, simply just select out of the table all of the other players where the last move date is less than or equal to the current player's last move date. If the number of rows is not 0, then the player cannot move yet.
The benefits of this approach is the simplicity- every time you allow a player to make a move, just update the column with the current date and time.
Your proposed solution seems a little circuitous:
You're updating+reading every player every move, when the minimum information you need to maintain is whose move it is.
You're losing information about player order as you encode next turn information.
A high-level solution:
Create a games table, one row per game, with a column like INT currentTurn
Create a gameUsers table on a per-game basis, linked to its game in games
Do assign each of the n users in gameUsers an INT playerOrder ranging [1-n]
Only accept a move from playerN if playerN == "SELECT playerID FROM gameUsers WHERE playerOrder = currentTurn"
After a successful move: "UPDATE games SET currentTurn = currentTurn + 1 WHERE game = thisGame"
I believe above table structure is a good object oriented representation of an actual game model. You can stash other per-game things into games like winner, length, date, etc. Pardon the pseudoSQL.
You could have a table with column hasMoved tinyint(1) required default 0, and query for where hasMoved == 0; if the query returns null, then all players have moved.
(Note: this is based on "must wait for all other users", NOT for a strict move order - i.e. 'A' must move before 'B' must move before 'C', etc.)
Additionally, queries using this method is somewhat slow and (to me) seems somewhat unnecessarily resource-intensive - perhaps think about using Ajax instead?
Have a game sequence number that starts at zero. Have a "last moved" number for each player. When a player moves, set their "last moved" number equal to the game sequence number. Once every player has moved, increment the game sequence number.
You may want to use a timeout though, otherwise a player who doesn't move can delay the other players indefinitely.
I would first determine $sequence by calculating speed. Then comparing speeds to determine order. Then use the order to send out notices for their move. Use a timestamp to ensure the user doesn't take over a day or however long, you will need a cron job just for this.
Have a variable or array hold the first n last sequence so u can easily move the last moved player to the back without mixing uP orders.
Have the page check the players order sequence and not allow action unless it's at 1 or 0. Be sure to sanitize inputs so no manipulation exists. Then insert your form and graphics and game equations.
You can save date-time of the last move of the each user. So when you DESC sort this table by this date-time column, you will have to fetch only the first row of the result, that will contain the ID of the allowed to make move player.

Categories