Here is the problem:-
I've got a table of results from sports matches called 'MatchResults' with the following fields
Player1
Player2
Player1GamesWon
Player2GamesWon
Player1Pts
Player2Pts
league_id
First I am running a query which will filter this table using a stored variable I already have, giving me a shorter collection of rows:-
$qry = "SELECT * FROM BadmintonMatchResults WHERE league_id = '$leagueid'";
I need to run through each row that is produced from the above query and use the values to update another table called 'LeagueTable'. The structure of LeagueTable is as follows:-
member_id
Played
Won
Lost
GamesWon
GamesLost
Difference
Points
These updates take the form of several SQL queries, for example:-
$qry = mysql_query("UPDATE LeagueTable SET Played = Played + 1 WHERE member_id = '$p1id'");
$qry = mysql_query("UPDATE LeagueTable SET Played = Played + 1 WHERE member_id = '$p2id'");
if($p1pts > $p2pts) {
$qry = mysql_query("UPDATE LeagueTable SET Won = Won + 1 WHERE member_id = '$p1id'");
$qry = mysql_query("UPDATE LeagueTable SET Lost = Lost + 1 WHERE member_id = '$p2id'");
}
else if($p2pts > $p1pts) {
$qry = mysql_query("UPDATE LeagueTable SET Won = Won + 1 WHERE member_id = '$p2id'");
$qry = mysql_query("UPDATE LeagueTable SET Lost = Lost + 1 WHERE member_id = '$p1id'");
}
$qry = mysql_query("UPDATE LeagueTable SET GamesWon = GamesWon + '$p1won' WHERE member_id = '$p1id'");
$qry = mysql_query("UPDATE LeagueTable SET GamesWon = GamesWon + '$p2won' WHERE member_id = '$p2id'");
$qry = mysql_query("UPDATE LeagueTable SET GamesLost = GamesLost + '$p1won' WHERE member_id = '$p2id'");
$qry = mysql_query("UPDATE LeagueTable SET GamesLost = GamesLost + '$p2won' WHERE member_id = '$p1id'");
$qry = mysql_query("UPDATE LeagueTable SET Difference = GamesWon - GamesLost");
$qry = mysql_query("UPDATE LeagueTable SET Points = Points + '$p1pts' WHERE member_id = '$p1id'");
$qry = mysql_query("UPDATE LeagueTable SET Points = Points + '$p2pts' WHERE member_id = '$p2id'");
Ignore any $variables I have as I'm currently doing this off data entered in a form, but want to alter it so that it uses rows from another database instead. I also know that my queries can be condensed and combined, my main problem is looping round this collection of queries multiple times for different sets of values.
My questions are:-
How to I reference the fields from the first table in the queries I need to run? Obviously just listing the field name 'Player1' isn't going to work.
How do I loop through each row and run the above 2 queries along with 8 more similar ones.
Note: Some of these queries are already nested inside an IF statement so any loop would have to go outside of that.
Any help would be much appreciated!
If you are going to do things that way then please tell me that you are sanitising the data before you use it in SQL statements. If I types " 0' or 1=1 " as my input and you used that the SQL would not do what you expect it to do.
To lop and then use the data by reference name from one tot he next you would simply do this:
if(mysql_num_rows($result)>0){
while($row = mysql_fetch_assoc($result)){
// ... your loop here code here
mysql_query("UPDATE LeagueTable SET Played = Played + 1 WHERE member_id = '" . $row['Player1'] . "'");
}
}
To be honest this still looks like you've got a very inefficient way of doing things as you are making your MySQL socket work very hard. I would consider how much calculations you need to store and how many can be worked out in an aggregate SQL query.
Related
I need to count the number of columns that have a specific value (1) in a specific row (250). The value of the row is variable according to the query.
I tried the code below, but it didn't work.
$total_r = mysqli_query($con, "SELECT * FROM registers WHERE ID = '$ID' AND 1 IN (column1, column2, column3, column4)";
$total = mysqli_num_rows($total_r);
echo $total;
I need the result as a number, lets say "2 columns" or something like that.
In MySQL Booleans become 0 or 1 in numerical context. So you could add expressions checking for a column to be equal to 1.
SELECT (column1 = 1)
+ (column2 = 1)
+ (column3 = 1)
+ (column4 = 1)
FROM registers
WHERE id = ?;
Check with below query
SELECT COUNT(*) TOT FROM registers WHERE ID = '$ID' AND column1='1' AND column2='1' AND column3='1' AND column4='1'
What finally did was a general query and then fetch and save every column value into a variable. Then i just added them, because the value of each column could be 0 or 1. Here is the code:
$query = mysqli_query($con, "SELECT * FROM registers WHERE ID = '$ID'");
$result = mysqli_fetch_array($query);
$column1 = $result['column1'];
$column2 = $result['column2'];
$column3 = $result['column3'];
$total = $column1 + $column2 + $column3;
If the column has a value = 0, will not be considered into the count.
I am trying to create a check-in/check-out table in my database. My check-in form works without issue, inserting the time into my database. The problem occurs when I try to check out. Everything is good on the first entry...
But when I try to check in and check out again, this happens...
So far so good, but when I check out...
Currently, my code updates the out column and totalTime column of all matching child_id's.
Here is my code:
// Select the correct child from the database
$sql_childID = "SELECT id FROM child
WHERE firstName = '$childFirstName'
AND lastName = '$childLastName'";
$result = $pdo->query($sql_childID);
$row = $result->fetch();
$var = $row['id'];
// Insert the check out time for the child
$query = "UPDATE checkinout
SET `out` = :nowTime
WHERE child_id = $var
AND `in` IS NOT NULL";
$statement = $pdo->prepare($query);
$statement->bindValue(':nowTime', date("YmjHis"));
$statement->execute();
// Select check in time for specified child
$sql_inTime = "SELECT `in` FROM checkinout
WHERE child_id = $var";
$inResult = $pdo->query($sql_inTime);
$inRow = $inResult->fetch();
$inTime = strtotime($inRow['in']);
// Select the check out time for specified child
$sql_outTime = "SELECT `out` FROM checkinout
WHERE child_id = $var";
$outResult = $pdo->query($sql_outTime);
$outRow = $outResult->fetch();
$outTime = strtotime($outRow['out']);
// Find total hours
$totalTime = abs($outTime - $inTime)/(60*60);
// Update totalHours column for specified child
$queryTotalTime = "UPDATE checkinout
SET totalTime = :totalTime
WHERE child_id = $var
AND 'out' IS NOT NULL";
$statement = $pdo->prepare($queryTotalTime);
$statement->bindValue(':totalTime', $totalTime);
$statement->execute();
I think you could do all of this in your first update statement using TIMESTAMPDIFF rather than figuring the total time with PHP:
UPDATE checkinout
SET
out = NOW(),
totalTime = TIMESTAMPDIFF(SECOND, `in`, NOW()) / 3600
WHERE
child_id = $var
AND out IS NULL
The criteria WHERE out IS NULL will only update rows that do not have a value in the out column yet.
IF you have MySQL Db THEN sql will be
SELECT TIMESTAMPDIFF(HOUR,in,out) from checkinout;
I have this table: tbl_module_bid
image:
you see users: Ali2,Ali,blackbone,dickface,mhmd
let's call for each one of them it's called $player and the sql query I wanna use in:
mysql_query("UPDATE `bbcsystem`.`tbl_admin` SET games_played = games_played + 1 WHERE username = $player");
I also don't want them to be duplicated
I tried using this script below:
//Update Game Played (not working very good):
$num_qry = "Select DISTINCT * From tbl_module_bid where user = '".$_SESSION['LOGIN_BALANCE_FRONT']['name']."' AND module = '$mod_id' order by bid asc";
$get_pick = $db->get_results($num_qry,ARRAY_A);
foreach($get_pick as $arr_pic)
{
$player = $arr_pic['user'];
mysql_query("UPDATE `bbcsystem`.`tbl_admin` SET games_played = games_played + 1 WHERE username = $player");
}
In the "user_id" column of my table, I'd like to insert the ID of the user who just registred from my page. The idea is to associate his recent generated income with the users id, just to spot an eventual double registration of the income.
In order to do this, I tought to update the user_id column, on the row where income_id has the biggest value, i.e. the last generated income, but something isn't working. My code is:
$query = "SELECT max( id_income ) FROM `affiliate_income`";
$last_income = mysql_query($query, $conn) or die(mysql_error());
$last = mysql_fetch_assoc($last_income);
$updtsql = "UPDATE affiliate_income SET `id_user`=".$row_user_code['id_user']."WHERE id_income =".$last;
$result = mysql_query($updtsql, $conn) or die(mysql_error());
any ideas?
Actually you can do it in one query,
UPDATE affiliate_income a
INNER JOIN (SELECT MAX(id_income) id_income FROM affiliate_income) b
ON a.id_income = b.id_income
SET a.id_user = 'valueHere'
You get the value of $last as array.So you have to giv the query like the following
$updtsql = "UPDATE affiliate_income SET `id_user`=".$row_user_code['id_user']."WHERE id_income =".$last['id_income'];
You try to get the max id_income but in the second query (updtsql) you try to find the id_income = array. Besides, you do not put a white space before WHERE clause.
$query = "SELECT max( id_income ) AS ii FROM `affiliate_income`";
$last_income = mysql_query($query, $conn) or die(mysql_error());
$last = mysql_fetch_assoc($last_income);
$updtsql = "UPDATE affiliate_income SET `id_user`=".$row_user_code['id_user']." WHERE id_income =".$last['ii'];
$result = mysql_query($updtsql, $conn) or die(mysql_error());
The function has next structure:
$q = 'LOCK TABLES table1 WRITE;';
mysql_query($q);
$q = 'select id from table1 where is_delete = 0 limit 1;';
$res = mysql_fetch_assoc(mysql_query($q));
if($res) {
$q = 'UPDATE table1 SET is_delete = 1 WHERE id = '".$res['id']."'';
mysql_query($q);
}
$q = 'UNLOCK TABLES;';
mysql_query($q);
I locking all tables, but queries run parallel.
How fix this?
Check whether you're getting any MySQL errors on the LOCK TABLES query:
$q = 'LOCK TABLES table1 WRITE';
$r = mysql_query($q) or die(mysql_error());
However, if this is all you are doing, you can also simply write:
UPDATE `table1 SET `is_delete` = 1 WHERE `is_delete` = 0 LIMIT 1
which does not require any locks at all. Of course, this will only work if the data from your first query is not being processed in any way, and if it doesn't really matter which row you are updating, as long as it's one in which is_delete is set to 0. This is what the code you posted does, too, but it's not immediately obvious to me what you would want to use this code for :)
More generally, if you are using the default InnoDB storage engine for your MySQL table, you may want to look into SELECT ... FOR UPDATE:
http://dev.mysql.com/doc/refman/5.0/en/innodb-locking-reads.html
You could write:
$q = 'select id from table1 where is_delete = 0 limit 1 for update';
$res = mysql_fetch_assoc(mysql_query($q));
if($res) {
$q = 'UPDATE table1 SET is_delete = 1 WHERE id = '".$res['id']."'';
mysql_query($q);
}
See also: http://www.mysqlperformanceblog.com/2006/08/06/select-lock-in-share-mode-and-for-update/