PHP increment statement according to value in database - php

I have created a PHP form with values that are inserted in the database. Fields dropdown boxes that are passed to the database after submit. According to what the user chooses in the dropdown box, score increases.
It contains age (dropdown box, >20 <20), degree (high school, university), etc.
What I want to build,is a function to add score values according to the choice of the dropdown box. Make specific column values a variable which adds scores points.
Every time someone inserts a specific choice, it should get a different amount of points.
Pseudocode, for score:
i = 0.
If dropdown.age>20 (choice 1), 5 points, i= i +5.
If dropdown.age<20, 10 points, i= i +10
If dropdownchoicebox.education = high school, 5 points, if university, 10 points.
Same for database
If age-row.value>20, i +5 else i+10
if education-row.value = highschool, i= i+5 else i + 10
And it should continue giving "score points", according to each specific choice in every field.
The code so far shows the database values. Each insert is in a different row until it runs out rows. For instance, age would be row 4, education row 5, etc.
<?php
// Get a db connection.
$db = JFactory::getDbo();
// Create a new query object.
$query = $db->getQuery(true);
// Select all records from the user profile table.
// Order it by the ordering field.
$query->select($db->quoteName(array(age, education, FieldName, FieldValue)));
$query->from($db->quoteName('table'));
// Reset the query using our newly populated query object.
$db->setQuery($query);
$row = $db->loadRow();
print_r($row);
// Load the results as a list of stdClass objects (see later for more options on retrieving data).
$results = $db->loadObjectList();
?>
Result: array value
Array ( [0] => over 20 [1] => highschool [2] => result 2[3] => result3
Names of rows: [0] = age, [1] = education.
What I want to do:
Button onclick: calculate points
function calculate points
//i for score
i=0
As 0 = over 20, i=0+5 = 5
as 1 = highschool i= 5+5 = 10

Related

php pdo code to create rows dynamically from user input?

column name = receipts (txtbox)
if user enter receipts = 5 then insert 5 rows in database.
data insert in table like this..
receipts
1
2
3
4
5
if user enter again receipts = 3 then again insert 3 rows in database.
6
7
8
like wise....
plz suggest me how to do this....
below is my code to save in php pdo...
i tried below code this is working but not inserting no in sequential order....
if(isset($_POST['save']))
{
$book_no = $_POST['book_no'];
$receipt= $_POST['receipt'];
for($row=1;$row<=$receipts ;$row++)
{
$insertrow = $database->insertRow("INSERT INTO scheme_master (book_no,receipt,created) VALUES (:book_no,:receipt)",
array(':book_no'=>$book_no,':receipt'=>$receipt));
}
}
First you have to change the following code:
$insertrow = $database->insertRow("INSERT INTO scheme_master (book_no,receipt,created) VALUES (:book_no,:receipt)",
array(':book_no'=>$book_no,':receipt'=>$receipt));
like this (the receipt number is the $row var, not the $receipt var)
$insertrow = $database->insertRow("INSERT INTO scheme_master (book_no,receipt,created) VALUES (:book_no,:receipt)",
array(':book_no'=>$book_no,':receipt'=>$row));
If you want that, the next time, it start from the last number inserted (that is, for example, start from 6, if the previous time you have inserted 5 receipts), you have to query the DB to get the the current max value, and then start from it. To get the max, a query like this should work:
SELECT MAX(receipt) FROM scheme_master where book_no = :book_no

how to get result from array?

I have an array as below :
Array
(
[VA-ecoclsqty2_0_R79_31_9_1Room1]=>2",
[VA-preco2-0_R79_31_9_1Room1]=>50.00",
[VA-amt_preco2-0_R79_31_9_1Room1]=>25.00",
[VA-busclsqty4_0_R79_31_9_1Room1]=>2",
[VA-prbus4-0_R79_31_9_1Room1]=>36.00",
[VA-amt_prbus4-0_R79_31_9_1Room1]=>18.00",
[VA-busclsqty5_1_R79_31_9_1Room2]=>1",
[VA-prbus5-1_R79_31_9_1Room2]=>17.00",
[VA-amt_prbus5-1_R79_31_9_1Room2]=>17.00",
[VA-ecoclsqty6_1_R79_31_9_1Room2]=>3",
[VA-preco6-1_R79_31_9_1Room2]=>28.00",
[VA-amt_preco6-1_R79_31_9_1Room2]=>14.00",
)
I want to insert above data as below rule...
insert data 8 (values as 2+2+1+3) rows where
2 row insert on VA-ecoclsqty.... - amount = 25.00, roomcode = R79_31_9_1, unique_id = 1 for Room1
2 row insert on VA-busclsqty.... - amount = 18.00, roomcode = R79_31_9_1, unique_id = 2 for Room1
1 row insert on VA-busclsqty.... - amount = 17.00, roomcode = R79_31_9_1, unique_id = 3 for Room2
3 row insert on VA-ecoclsqty.... - amount = 14.00, roomcode = R79_31_9_1, unique_id = 4 for Room2
and more for different rooms for multiple rows.
How can i insert it?
And please remember that every key is different from each other.
Please reply soon and try to help.
To use ajax for the form I'd look at jQuery ajax function. To process the form and perform a search in you DB you'll have to setup a URL for the form to post to that does the processing and returns the correct response.

results table in php

I am having trouble understanding how a loop I have created works.
I have input fields on another page, which where results are sent to the results table in my database, with team name, team score, opposition score, opposition name.
Now the page where the results are entered mirrors the current contents of the results table so that previously entered scores appear already in the correct input field, and the ones with no socres enetered are at 0.
This page works perfectly in that a score that is edited, replaces the score in the results table, blank ones are left blank etc.
Howwever, I need to use these results to update my league table table in my database.
Currently I have a rather large loop, which (after I have fetched team name, team score, opposition score, opposition name, from the results table), works out how many points to give that team, and the opposing team, plus how many to add to the 'win' column and the 'loss' column etc of my league table.
The problem I have is that it will only ever do one result per team, because on each iteration of the loop, as soon as it finds a matching if statement (ie if team_score>opposition score) it updates the table, before running through the other results to find that teams results.
Because an edited result needs to be treated as an edited result, not an additional result, this is the only way I have been able to find to get even close.
here is a snippet of the code. There are many more if statementswithin the for loop but they are not needed to describe the problem I am having.
$query = $database->query("SELECT team_name, team_score, opposition_score, opposition_name from results_a");
while ($row = $query->fetch(PDO::FETCH_NUM)) {
$team[] = ($row[0]);
$team_score[] = ($row[1]);
$opposition_score[] = ($row[2]);
$opposition[] = ($row[3]);
}
$count=count($team);
for ($i = 0; $i < $count; $i++) {
$team_bonus[$i] = $team_score[$i] / 2;
$opposition_bonus[] = $opposition_score[$i] / 2;
//TEAM WINS, NO OPPOSITION BONUS
else if (($team_score[$i] > $opposition_score[$i]) && ($team_bonus[$i] > $opposition_score[$i])) {
$team_points[]+=3;
$team_win[]+=1;
$team_draw[]+=0;
$team_loss[]+=0;
$team_extra[]+=0;
$opposition_points[]+=0;
$opp_win[]+=0;
$opp_draw[]+=0;
$opp_loss[]+=1;
$opp_extra[]+=0;
$team_played[]+=1;
$opposition_played[]+=1;
}
$team_gd[] = $team_score[$i] - $opposition_score[$i];
$opposition_gd[] = $opposition_score[$i] - $team_score[$i];
//UPDATE LEAGUE TABLE
$query = $database->query("UPDATE pool_a SET played='$team_played[$i]',
win='$team_win[$i]',
draw='$team_draw[$i]',
loss='$team_loss[$i]',
goals_for='$team_score[$i]',
goals_against='$opposition_score[$i]',
goal_difference='$team_gd[$i]',
bonus_points='$team_extra[$i]',
points='$team_points[$i]'
where team_name = '$team[$i]'");
$query2 = $database->query("UPDATE pool_a SET played='$opposition_played[$i]',
win='$opp_win[$i]',
draw='$opp_draw[$i]',
loss='$opp_loss[$i]',
goals_for='$opposition_score[$i]',
goals_against='$team_score[$i]',
goal_difference='$opposition_gd[$i]',
bonus_points='$opp_extra[$i]',
points='$opposition_points[$i]'
where team_name='$opposition[$i]'");
The+= within the if statement are useless, because instead of going to the next row where the team name is the first teams name, it runs the query, then when that teams name appears again, it replaces the data next time the query runs.
Very stuck, have spent a lot of time on this!
If you need any more info let me know.
Many thanks

Selecting and updating any number of rows in large table using CodeIgniter

I've got a large table, about 10 million rows, and I'm trying to build a function that selects a random number of rows (anything between 1 and all), updates a field on the selected rows to x (winner) and updates the field on remaining rows to y (loser).
All rows have a unique id but not all rows will be selected from (the table has competition entries for a number of competitions but the function needs to select winners for one competition only).
I've considered ordering by random but it's too slow for a big table.
I've also considered assigning a random value into the row when it's inserted into the table so that it can be used to order but it would have to be unique and there can be batch updates for thousands of rows so it would be slow to assign a unique random value to each row.
There's too much data to save the result as an array and shuffle.
Can anyone suggest other solutions?
This is how I would do it if the table wasn't huge:
function getWinnersLosers($winnercount,$allwinners) {
// Must have draw id and ticketstatus id
if ( ! $this->draw_id || ! $this->ticketstatus_id ) return false;
// Update winners
$this->db->where('draw_id', $this->draw_id);
$this->db->where('ticketstatus_id', CONST_TICKETSTATUS_ENTERED);
$this->db->order_by('id', 'RANDOM');
if ( ! $allwinners ) $this->db->limit($winnercount);
$data = array( 'ticketstatus_id' => CONST_TICKETSTATUS_WINNERUNCLAIMED );
$query = $this->db->update('drawtickets',$data);
// Update losers (remaining tickets)
$this->db->where('draw_id', $this->draw_id);
$this->db->where('ticketstatus_id !=', CONST_TICKETSTATUS_WINNERUNCLAIMED);
$data = array( 'ticketstatus_id' => CONST_TICKETSTATUS_LOSE );
$query = $this->db->update('drawtickets',$data);
}

Insert multiple rows in MySQL and check for random string without long delay (~80 rows each minute)

For a research project I am obtaining data from a local bus company's GPS system (through their API). I created a php cron job that runs every minute to obtain data like the vehicle, route ID, location, destination, etc. The data did not contain a unique "run number" for each bus route (a unique number so that I can track the progression of a single bus along its route), so I created my own that checks if the vehicle ID, destination, and relative time are similar, and assigns the unique "run ID" to it so that I can track the bus along its route. If no run ID exists, a random one is generated. (Any vehicle with the same "vid" and "pid" within 2 minutes of the last inserted row "timeadded" is on the same run, and this is important for my research)
Each time the cron runs (1 minute), approximately 80 rows are added into the database.
Initially the job would run quickly. However, with over 500,000 rows now, I've noticed the job can take upwards of 40 seconds. I believe it's because for each of the ~80 rows, it has to check the entire table ("vehicles") to see if the same run ID exists, essentially querying a large table and inserting a row 80 times. I want to get at least a week's worth of data (on day 4 now), at which point I can export the data, erase all rows, and start over. My question is: Is there any way I can refactor my PHP/SQL code to make the process run faster? It's been years since I've worked with SQL, so I'm sure there's a more ingenious way to insert all this data.
<?php
// Obtain data from XML
$xml = simplexml_load_file("url.xml");
foreach ($xml->vehicle as $vehicle) {
$vid = $vehicle->vid;
$tm = $vehicle->tmstmp;
$dat = substr($vehicle->tmstmp, 0, 8);
$tme = substr($vehicle->tmstmp, 9);
$lat = $vehicle->lat;
$lon = $vehicle->lon;
$hdg = $vehicle->hdg;
$pid = $vehicle->pid;
$rt = $vehicle->rt;
$des = $vehicle->des;
$pdist = $vehicle->pdist;
// Database connection and insert
mysql_connect("redacted", "redacted", "redacted") or die(mysql_error()); mysql_select_db("redacted") or die(mysql_error());
$sql_findsim = "SELECT vid, pid, timeadded, run, rt FROM vehicles WHERE vid=" . mysql_real_escape_string($vid). " AND pid=" . mysql_real_escape_string($pid). " AND rt=" . mysql_real_escape_string($rt). " AND timeadded > DATE_SUB(CURRENT_TIMESTAMP, INTERVAL 2 MINUTE);";
$handle = mysql_query($sql_findsim);
$row = mysql_fetch_row($handle);
$runid = $row[3];
if($runid !== null) {
$run = $runid;
} else {
$run = substr(md5(rand()), 0, 30);
}
$sql = "INSERT INTO vehicles (vid, tmstmp, dat, tme, lat, lon, hdg, pid, rt, des, pdist, run) VALUES ($vid,'$tm','$dat','$tme','$lat','$lon',$hdg,$pid,'$rt','$des',$pdist,'$run')";
$result = mysql_query($sql);
mysql_close();
}
?>
Thanks for any help with refactoring this code to get it to run more quickly and efficiently.
Do you have any indexes on the table? A compound index on (vid,pid,rt,timeadded) will make the query faster, avoiding a full table scan.
create index fastmagic on vehicles (vid,pid,rt,timeadded)
Alternatively, you could skip the select all together and just to the insert without assigning the "run" random value. This will keep your cron job at "constant time" since all you're doing is appending new data.
After you've got your week of data go back and write "second pass" code to step through each row (select * from vehicle order by timeadded). For each row, do your "select" similar to how you've already done it - then "update" the row you are processing now.
If you go with the alternate, you'll probably want an autoincrement "id" integer column to make row identification clearer (if you don't already have one).
I would suggest that,
Create a table as vehicle_ids ( or some meaningful name ) these fields.
vid, pid, run, rt
instead of checking in vehicles table for vid, you can check the above table for id, if not insert ( make vid as auto increment ).
Normalize your table and also index your vehicle table

Categories