I'm trying to optimize this check I have. I need to check table called lines and see if any row has matching Earned and Maxearned values (only rows with Position 1,2,3,4). If they do, I need to grab Earned from that row, write it in a different table called bank and remove that row from table called lines. This is what I have:
$sql3 = "SELECT * FROM `lines` WHERE Position <= 4 AND Linenum = '$linenum' AND Earned = Maxearned";
$result3 = mysql_query($sql3);
if (mysql_num_rows($result3) != 0)
{
while ($row3 = mysql_fetch_array($result3))
{
$users[] = $row3['User'];
}
foreach ($users as $user)
{
$sql6 = "SELECT * FROM `lines` WHERE Position <= 4 AND Linenum = '$linenum' AND Earned = Maxearned AND User = '$user'";
$result4 = mysql_query($sql6);
while ($row4 = mysql_fetch_array($result4))
{
$earned = $row4['Earned'];
}
$today = date("Y-m-d");
$method = "Queue money";
$type = "Earned";
$status = "Completed";
$sql4 = "INSERT INTO bank (User,Amount,Method,Transdate,Type,Status) VALUES ('$user','$earned','$method','$today','$type','$status')";
$sql5 = "DELETE FROM `lines` WHERE Position <= 4 AND Linenum = '$linenum' AND Earned = Maxearned AND User = '$user'";
}
$sql7 = "UPDATE `lines` SET Position = Position - 1 WHERE Linenum = '$linenum'";
}
I'm trying to avoid having to run a different query ($sql6 and the while after that) to grab the value of Earned column. Is there a way to do this? I've tried everything and this is pretty much the best I came up with.
You can do something like this:
mysql_query("SET AUTOCOMMIT=0");
mysql_query("START TRANSACTION");
$sql3 = "SELECT * FROM `lines` WHERE Position <= 4 AND Linenum = '$linenum' AND Earned = Maxearned";
$result3 = mysql_query($sql3);
if (mysql_num_rows($result3) != 0)
{
while ($row3 = mysql_fetch_array($result3))
{
$users[] = $row3['User'];
}
$users_to_compare = "(" . rtrim(implode(",", $users),',') . ")";
$sql4 = "SELECT * FROM `lines` WHERE Position <= 4 AND Linenum = '$linenum' AND Earned = Maxearned AND User IN $users_to_compare";
$result4 = mysql_query($sql4);
while ($row4 = mysql_fetch_array($result4))
{
$earned = $row4['Earned'];
$today = date("Y-m-d");
$method = "Queue money";
$type = "Earned";
$status = "Completed";
$sql5 = "INSERT INTO bank (User,Amount,Method,Transdate,Type,Status) VALUES ('{$row4['User']}','$earned','$method','$today','$type','$status')";
$result5 = mysql_query($sql5);
}
$sql6 = "DELETE FROM `lines` WHERE Position <= 4 AND Linenum = '$linenum' AND Earned = Maxearned AND User IN $users_to_compare";
$result6 = mysql_query($sql6);
$sql7 = "UPDATE `lines` SET Position = Position - 1 WHERE Linenum = '$linenum'";
$result7 = mysql_query($sql7);
if ($result5 && $result5 && $result7) {
mysql_query("COMMIT");
} else {
mysql_query("ROLLBACK");
}
}
Going one step further you can also use Batch INSERT for you insert queries
Note: Dont forget that mysql_* versions are depreceated you should use mysqli_*
Related
I use this code below to determine the position of each student result based on the percentage score of their subject, the program assigned their position as (1st, 2nd, 2nd, 4th ...)
My challenge now is that whenever the percentage score is 100, the system position the student as last in the class instead of 1st position.
Below is the code:
<?php
session_start();
include("DB/config.php");
ini_set('max_execution_time', 1000000);
$class_arm= $_SESSION['clas'];
$queris = "select * from setup";
$result3 = mysqli_query($con,$queris) or die(mysqli_error($con));
$rws3 = mysqli_fetch_assoc($result3);
$ses3=$rws3['section'];
$term3=$rws3['term'];
$query_sj = "SELECT subj FROM sec_result where class='$class_arm' and year='$ses3' and term='$term3' and tsc<>'' and tsc is not null and tsc <> '0'";
$result_sj = mysqli_query($con,$query_sj) or die(mysqli_error($con));
while($row_sj = mysqli_fetch_array($result_sj)){
$query = "SELECT distinct studid,subj,tsc FROM sec_result where class='$class_arm' and year='$ses3' and term='$term3' and subj='".$row_sj['subj']."' ORDER BY tsc DESC";
$result = mysqli_query($con,$query) or die(mysqli_error($con));
/*$row2 = mysqli_fetch_array( $result );
echo $row2['tsc'];
exit;*/
if( !$result ){
echo 'SQL Query Failed';
}else{
$rank = 0;
$last_score = false;
$rows = 0;
while( $row = mysqli_fetch_array( $result ) ){
$rows++;
if( $last_score!= $row['tsc'] ){
$last_score = $row['tsc'];
$nuval = $row['tsc'];
$rank = $rows;
}
mysqli_query($con,"UPDATE sec_result SET pos = '$rank' where studid='".$row['studid']."' and year='$ses3' and term='$term3' and subj='".$row_sj['subj']."'") or die(mysqli_error($con));
}
}
}
?>
My expectation is that the student that scores 100 percent should be given the first position.
Please, I need your help to resolve this, Thanks.
My expectation is that the student that scores 100 percent should be given the first position.
how do i optimize the following code?
How I can reduce the 4 loops to one, they are almost always the same MySQL statements. Only the step value in the WHERE is always different.
Currently the loading time for this part in the code is about 5-7 sec and that is too long ... each loop make max. 200-300 passes.
// Tank battles heute MySQL
$tday = array();
$result2 = mysqli_query($db, "SELECT * FROM activity_day_account_vehicles WHERE account_id = '$me_id' AND step = '$step'");
while($row_tday = mysqli_fetch_assoc($result2)) {
$t_id = $row_tday['tank_id'];
$tday[$t_id] = $row_tday['statistics_battles'];
}
// Tank battles gestern MySQL
$tday2 = array();
$result3 = mysqli_query($db, "SELECT * FROM activity_day_account_vehicles WHERE account_id = '$me_id' AND step = '$step2'");
while($row_tday2 = mysqli_fetch_assoc($result3)) {
$t_id = $row_tday2['tank_id'];
$tday2[$t_id] = $row_tday2['statistics_battles'];
}
// Tank battles Woche MySQL
$tweek = array();
$result4 = mysqli_query($db, "SELECT * FROM activity_day_account_vehicles WHERE account_id = '$me_id' AND step = '$step3'");
$menge2 = mysqli_num_rows($result4);
if ($menge2 === 0) {
$result4 = mysqli_query($db, "SELECT * FROM activity_day_account_vehicles WHERE account_id = '$me_id' ORDER BY step ASC LIMIT $anzahl2");
}
while($row_tweek = mysqli_fetch_assoc($result4)) {
$t_id = $row_tweek['tank_id'];
$tweek[$t_id] = $row_tweek['statistics_battles'];
}
// Tank battles Monat MySQL
$tmonth = array();
$result5 = mysqli_query($db, "SELECT * FROM activity_day_account_vehicles WHERE account_id = '$me_id' AND step = '$step4'");
$menge2 = mysqli_num_rows($result5);
if ($menge2 === 0) {
$result5 = mysqli_query($db, "SELECT * FROM activity_day_account_vehicles WHERE account_id = '$me_id' ORDER BY step ASC LIMIT $anzahl2");
}
while($row_tmonth = mysqli_fetch_assoc($result5)) {
$t_id = $row_tmonth['tank_id'];
$tmonth[$t_id] = $row_tmonth['statistics_battles'];
}
Create indexes on account_id and step:
CREATE INDEX activity_day_account_vehicles_001
ON activity_day_account_vehicles (account_id);
CREATE INDEX activity_day_account_vehicles_002
ON activity_day_account_vehicles (step);
I'm still learning PHP & MySQL and the following has confused me for a long time and I'm looking for some guidance as to how I'd be able to do this.
Basically, I have a HTML table which is displayed by an echo which grabs the values from a MySQL database, the table displays Position, User, Today. Weekly & Monthly. The rows that the table displays is dependent on how many users are logged in so if 10 people are logged in, 10 rows will be displayed, 5 users = 5 rows etc. To achieve this I created a loop which displays the information for each logged in user and this is where I think the issue starts with sorting the data. This is what is used to display the data:
<?php
$counter = 1;
include_once 'config.php';
$sql = "SELECT * FROM vicidial_live_agents";
$result = $conn->query($sql);
while($row = $result->fetch_assoc())
{
$dateNow = date('Y-m-d H:i:s');
$dateNow = strtotime($dateNow);
$dateOld = $row['last_state_change'];
$dateOld = strtotime($dateOld);
$dateDiff = $dateNow - $dateOld;
if ($row['status'] == "INCALL") {
$colour = "w3-green";
}
elseif ($row['status'] == "READY") {
$colour = "w3-yellow";
}
elseif ($row['status'] == "PAUSED") {
$colour = "w3-grey";
}
elseif ($row['status'] == "DEAD") {
$colour = "w3-red";
}
$user = $row['user'];
echo
'<tr class="'.$colour.'">
<td class="w3-xlarge">'.$counter.'</td>
<td class="w3-xlarge">'.$user.'</td>';
$sql2 = "SELECT count(status) AS sales FROM vicidial_agent_log WHERE user = '$user' AND DATE(event_time) = CURDATE() AND status = 'SALE'";
$result2 = $conn->query($sql2);
while($row2 = $result2->fetch_assoc())
{
echo
'<td class="w3-xlarge">'.$row2['sales'].'</td>';
$sql3 = "SELECT count(status) AS salesWeek FROM vicidial_agent_log WHERE user = '$user' AND WEEK(event_time) = WEEK(CURDATE()) AND YEAR(event_time) = YEAR(CURDATE()) AND status = 'SALE'";
$result3 = $conn->query($sql3);
while($row3 = $result3->fetch_assoc())
{
echo
'<td class="w3-xlarge">'.$row3['salesWeek'].'</td>';
$sql4 = "SELECT count(status) AS salesMonth FROM vicidial_agent_log WHERE user = '$user' AND MONTH(event_time) = MONTH(CURDATE()) AND YEAR(event_time) = YEAR(CURDATE()) AND status = 'SALE'";
$result4 = $conn->query($sql4);
while($row4 = $result4->fetch_assoc())
{
echo
'<td class="w3-xlarge">'.$row4['salesMonth'].'</td>
</tr>';
$counter++;
}
}
}
}
?>
What I want is for the table to be sorted by highest monthly sales with the highest being at the top and lowest at the bottom.
I have done some research and the solutions I've found I could not get to work with this situation for example, a JS sort from W3Schools wouldn't work and I think this is due to the values being called from the database.
I hope this is clear, any advice on how to tackle this is appreciated :)
UPDATED
I'm trying to create a basic schedule for all students in their final year to present their final project to 2 supervisors. I have successfully created a schedule with no constraints but now i need to create a schedule based on the supervisors availability.
Here is a detailed description of the problem.
A student is assigned a supervisor and a supervisor will supervise more than one student. The supervisor also teaches classes during the day. Now i need to create a schedule for all of the students to present to their supervisor and one additional supervisor that supervises other students. (for the moment I'm focusing on the supervisors that are assigned to the student and not the second one until i get it working.
I want to compare the supervisors availability for the slots time if they're free then assign them to the slot and then update the availability of that time to false to avoid double booking using a PHP sql query.
so...
What i have done so far:
// get all of the Slots.
$sql = "SELECT Slot_ID FROM slot WHERE StartTime < '18:00:00'";
$result = mysqli_query($con, $sql);
$DayTimeSlots = array();
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
$DayTimeSlots [] = $row;
}
}
// Store slots into simple array
function extractSlotId($DayTimeSlots){
return $DayTimeSlots['Slot_ID'];
}
$slots = array_map("extractSlotId",$DayTimeSlots);
// SHOW SLOTS
foreach ($slots as $slotID) {
echo " SlotID: = $slotID <br>";
}
// Get All students
$sql = "SELECT Student_ID FROM student WHERE PartTime =0";
$result = mysqli_query($con, $sql);
$FullTimeStudents = array();
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
$FullTimeStudents [] = $row;
}
}
// Store into a simple array
// Extract student id and Supervisor_ID
function extractStudentId($FullTimeStudents){
return $FullTimeStudents['Student_ID'];
}
$students = array_map("extractStudentId",$FullTimeStudents);
// Combine the Slot and Students array
$min = min(count($FullTimeStudents), count($DayTimeSlots));
$result = array_combine(array_slice($students , 0, $min), array_slice($slots, 0, $min));
foreach($result as $key=>$value){ // $Key = Student_ID, $value = Slot_ID
echo " $key : $value ";
// get supervisor ID
$sql = "select Supervisor_ID FROM student where Student_ID = $key";
$query = mysqli_query($con, $sql);
$row = mysqli_fetch_array($query);
$SuperID = $row['Supervisor_ID'];
echo "SuperID : $SuperID ";
// get slotID
$sql = "select Date, StartTime FROM Slot where Slot_ID = $value";
$query = mysqli_query($con, $sql);
$row = mysqli_fetch_array($query);
$Date = $row['Date'];
$StartTime = $row['StartTime'];
echo "Slot Date : $Date Start Time : $StartTime ";
// get Date id
$sql = "select Date_ID FROM dates where Date = '$Date'";
$query = mysqli_query($con, $sql);
$row = mysqli_fetch_array($query);
$DateID = $row['Date_ID'];
echo "Date ID : $DateID ";
// Check if the supervisor is available
$sql = "select `$StartTime` FROM supervisor_availability where Date_ID = $DateID AND Supervisor_ID = $SuperID";
$query = mysqli_query($con, $sql);
$row = mysqli_fetch_array($query);
$Available = $row["$StartTime"];
echo "Is the Lecture Available? : $Available ";
$Time = "`$StartTime`";
if($Available == 1){
$sql = "INSERT INTO student_slot (Student_ID, Slot_ID) VALUES ($key, $value)";
$result = mysqli_query($con, $sql);
$sql = "UPDATE `supervisor_availability` SET $Time = '0' WHERE `supervisor_availability`.`Supervisor_ID` = $SuperID AND `supervisor_availability`.`Date_ID` = $DateID" ;
$result = mysqli_query($con, $sql);
} else if ($Available == 0) {
// Not sure what to do here.
// Can i make the Slot it's currently checking go to the end of the
// array for a different student and then check the next slot and come
// back to it.
}
}
I'm using echo for debugging.
The algorithm works fine if the Supervisor is available, it assigns it correctly and then updates the Supervisors availability for that time slot
Just need help with how to handle it if they're not available.
Any help or advice would be appreciated.
Supervisor_Availability Slot Table Student Table Date Table DB_Structure
I'm trying to design a PHP browser game just for fun and practice. I'm currently working on the combat script and I encountered an endless loop. I can't figure out the reason why it's happening. Anyways, here's the code:
<?php
session_start();
// Script PHP pentru simularea luptelor single player
/*
1 = Magic
2 = Attack
3 = Defence
5 = Maximum HP
6 = Current HP
4 = Gold coins
17 = Experience
*/
require_once("config.php");
$username = $_SESSION['username'];
$query = ("SELECT id FROM users WHERE username = '$username'");
$user_id = mysql_query($query) or die (mysql_error());
// Momentan monstrii sunt alesi in mod aleatoriu
$query = ("SELECT id FROM monsters ORDER BY RAND() LIMIT 1");
$monster_id = mysql_query($query) or die (mysql_error());
$query = ("SELECT value FROM user_stats WHERE stat_id = 6 AND user_id = '$user_id'");
$player_hp = mysql_query($query) or die (mysql_error());
$query = ("SELECT value FROM monster_stats WHERE stat_id = 5 AND monster_id = '$monster_id'");
$monster_hp = mysql_query($query) or die (mysql_error());
if ($player_hp <= 0)
{
$query = ("SELECT value FROM user_stats WHERE stat_id = 4 AND user_id = '$user_id'");
$player_gc = mysql_query($query) or die (mysql_error());
$query = ("SELECT value FROM monster_stats WHERE stat_id = 4 AND user_id = '$monster_id'");
$monster_gc = mysql_query($query) or die (mysql_error());
$query = ("SELECT value FROM user_stats WHERE stat_id = 17 AND user_id = '$monster_id'");
$player_exp = mysql_query($query) or die (mysql_error());
$query = ("SELECT value FROM monster_stats WHERE stat_id = 17 AND monster_id = '$monster_id'");
$monster_exp = mysql_query($query) or die (mysql_error());
$player_gc = $player_gc + $monster_gc;
$player_exp = $player_exp + $monster_exp;
// item drop trebuie facut
echo "Congratulations! You won the battle and you gained " . $monster_gc . " gold coins and " . $monster_exp . " experience points.";
}
elseif ($monster_hp <= 0)
{
echo "You lost the battle.";
}
else
{
$query = ("SELECT value FROM user_stats WHERE stat_id = 1 AND user_id = '$user_id'");
$player_magic = mysql_query($query) or die (mysql_error());
$query = ("SELECT value FROM monster_stats WHERE stat_id = 1 AND monster_id = '$monster_id'");
$monster_magic = mysql_query($query) or die (mysql_error());
$query = ("SELECT value FROM user_stats WHERE stat_id = 2 AND user_id = '$user_id'");
$player_attack = mysql_query($query) or die (mysql_error());
$query = ("SELECT value FROM monster_stats WHERE stat_id = 2 AND monster_id = '$monster_id'");
$monster_attack = mysql_query($query) or die (mysql_error());
$query = ("SELECT value FROM user_stats WHERE stat_id = 3 AND user_id = '$user_id'");
$player_defence = mysql_query($query) or die (mysql_error());
$query = ("SELECT value FROM monster_stats WHERE stat_id = 3 AND monster_id = '$monster_id'");
$monster_defence = mysql_query($query) or die (mysql_error());
$turn = rand(0,1);
while (($player_hp > 0) && ($monster_hp > 0) &&($turn < 6))
{
$turn++;
// Player turn
if ($turn % 2 == 0)
{
echo $monster_hp . "<br>";
$monster_hp -= ($player_attack + $player_magic / 2 - $monster_defence - $monster_magic / 2);
var_dump ($monster_hp);
}
// Monster turn
else
{
echo $player_hp . "<br>";
$player_hp -= ($monster_attack + $monster_magic / 2 - $player_defence - $player_magic / 2);
var_dump ($player_hp);
}
}
}
?>
The while is down in the else. I know that MySQL is depreciated. Thanks!
Are you after this (operator is -= not -):
// Player turn
if ($turn % 2 == 0)
{
$monster_hp -= ($player_attack + $player_magic / 2 - $monster_defence - $monster_magic / 2);
}
// Monster turn
else
{
$player_hp -= ($monster_attack + $monster_magic / 2 - $player_defence - $player_magic / 2);
}
-edit- if your variable is Resource id #5 etc, it means you haven't correctly retried your MySQL data from PHP. Try this:
$query = ("SELECT value FROM user_stats WHERE stat_id = 3 AND user_id = '$user_id'");
$player_defence = mysql_query($query) or die (mysql_error());
$player_defence = mysql_fetch_assoc($player_defence);
$player_defence = $player_defence['value'];
You'll need to do that (or something similar) for every query result you're getting. It converts your query result to an associate array then to the variable you need.
Manual: http://php.net/manual/en/function.mysql-fetch-assoc.php
In your while loop you never actually CHANGE the HPs of the monsters and players:
$monster_hp - ($player_attack + $player_magic / 2 - $monster_defence - $monster_magic / 2);
Did you mean to use something like this instead:
$monster_hp -= ($player_attack + $player_magic / 2 - $monster_defence - $monster_magic / 2);
The -= operator is really a quick way of programming equals itself minus...:
// The following lines are identical in logic:
$var-=1
$var=$var-1;