Query (mysql) should only update if $sqltext < $_POST[Score] - mysql

I have the following query:
$sqltext = "SELECT Score FROM HighScore ".
"WHERE fbID='$_POST[fbID]' AND ".
"Layout='$_POST[Layout]'";
$result = mysql_query($sqltext);
if(mysql_num_rows($result)>0){
$sql = "UPDATE HighScore SET Score = '$_POST[Score]', ".
"Time = '$_POST[Time]', ".
"Stars = '$_POST[Stars]' ".
"WHERE fbID = '$_POST[fbID]' AND Layout = '$_POST[Layout]'";
} else {
$sql = "INSERT INTO HighScore (fbID, Layout, Score, Time, Stars) ".
"VALUES ('$_POST[fbID]','$_POST[Layout]',".
"'$_POST[Score]','$_POST[Time]','$_POST[Stars]')";
}
What does it do? Well it checks if a row is in the database or not (there is always just 1 row or none). If there is no row, it inserts a new one in the database. If the row is present it will update the row. This all works OK.
$sqltext will give a value. This value can be 234, 3424342 or even -392. If this value is smaller than the '$_POST[Score]' value, it should update the row. Currently it doesn't and I can't seem to get this working properly. So how can I make it so, that if $sqltext (which is Score from the db) < '$_POST[Score]' it should update the row and else ignore it? (also not insert).

You could also add a UNIQUE KEY constraint on (fbID, Layout) and then just use one query:
$sql = "
INSERT INTO HighScore
(fbID, Layout, Score, Time, Stars)
VALUES ( '$_POST[fbID]', '$_POST[Layout]'
, '$_POST[Score]', '$_POST[Time]', '$_POST[Stars]'
)
ON DUPLICATE KEY
UPDATE
Score = GREATEST(Score, VALUES(Score))
, Time = VALUES(Time)
, Stars = VALUES(Stars)
";

$sqltext= "SELECT Score FROM HighScore WHERE fbID='$_POST[fbID]'AND Layout='$_POST[Layout]'"; $result = mysql_query($sqltext);
if(mysql_num_rows($result)>0){
if ($row = mysql_fetch_assoc($result))
{
if ($row['Score'] < $_POST['Score'])
{
$sql="UPDATE HighScore SET Score = '$_POST[Score]', Time = '$_POST[Time]', Stars = '$_POST[Stars]' WHERE fbID = '$_POST[fbID]' AND Layout = '$_POST[Layout]'";
}
}
}else{
$sql="INSERT INTO HighScore (fbID, Layout, Score, Time, Stars) VALUES ('$_POST[fbID]','$_POST[Layout]','$_POST[Score]','$_POST[Time]','$_POST[Stars]')";
}
I think this is what you want. But it does not do anything, if there is a row AND the score is higher than the Score in POST['Score']

Related

How to copy a row from one mysql table to another

Please forgive if already answered. I have looked at lots of other questions and none are helping! Basically, I want to copy a single row from one table, to another table. The problem I have struck, is the the id of the row I want to copy, is already in use, in the table I want to copy to. This is what I have at present, it works, until it strikes this problem.
INSERT INTO venues SELECT * FROM submitted_venues WHERE id='9';
It generates the error: Duplicate entry '9' for key 'id'
Is there a way to change the id number on the fly, so that it create an unused new number for the receiving table, or do I have to write a query that names and gets all of the fields for each table. Some thing like the replace statement 0 cases would be good, where 0 creates a new record!!
The 9, is just a number that I used for this example, of course it changes.
EDIT:
I have created a work around for this problem.
//get highest id number of table to copy to
$sql = "SELECT id FROM venues ORDER BY id DESC LIMIT 1";
if( $result = mysqli_query( $mysqli, $sql ) ){
$row = mysqli_fetch_array($result);
$to_id = $row[ 0 ];
//increase id
$to_id ++;
//get highest id number of table to copy from
$sql = "SELECT id FROM submitted_venues ORDER BY id DESC LIMIT 1";
if( $result = mysqli_query( $mysqli, $sql ) ){
$row = mysqli_fetch_array($result);
$from_id = $row[ 0 ];
//increase id
$from_id ++;
//get highest unused id number
$temp_id = $to_id > $from_id ? $to_id : $from_id;
//update existing record to ensure that its id number will not conflict
$sql = "UPDATE submitted_venues SET id = '$temp_id' WHERE id='$current_venue_id'";
if( $result = mysqli_query( $mysqli, $sql ) ){
$current_venue_id = $temp_id;
//copy record to normal regular venues table
$sql = "INSERT INTO venues SELECT * FROM submitted_venues WHERE id='$current_venue_id'";
if( ! $result = mysqli_query( $mysqli, $sql ) )
die("Could not copy -> " . mysqli_error($mysqli) );
//delete record from temp db table
$sql = "DELETE FROM submitted_venues WHERE id='$current_venue_id'";
if( ! $result = mysqli_query( $mysqli, $sql ) )
die("Could not delete -> " . mysqli_error($mysqli) );
}
}
}

Updating Multiple Column on MySQL

I want to update members_roosevelt table ACCOUNT column starting with 3000+ value I also want to update ACCOUNT column on loan_roosevelt table that is related to my member_roosevelt. What's wrong with my query? Thank you!
$query1 = "SELECT ACCOUNT
FROM
`members_roosevelt`";
$result_q1 = $link->query($query1) or die($link->error);
while ($obj = $result_q1->fetch_object()) {
$members[] = $obj->ACCOUNT;
}
$ids = implode(',', $members);
$sql = "UPDATE `members_roosevelt` as `memb`
JOIN `loan_roosevelt` as `loan`
ON `memb`.`ACCOUNT` = `loan`.`ACCOUNT`
SET
(`memb`.`ACCOUNT`,
`loan`.`ACCOUNT`) = CASE ACCOUNT";
foreach ($members as $id => $ordinal) {
$sql .= sprintf("WHEN %d THEN %d ", $ordinal, (3000+$id));
}
$sql .= "END WHERE memb.ACCOUNT IN ($ids)";
$link->query($sql) or die($link->error);
SET (`memb`.`ACCOUNT`, `loan`.`ACCOUNT`) = CASE ACCOUNT...
This is simply not part of SQL syntax. You can't set two columns at a time like this. The left side of an assignment operator must be one column.
A better solution is to use a session variable.
SET #acct = 3000;
UPDATE members_roosevelt as memb
JOIN loan_roosevelt as loan
ON memb.ACCOUNT = loan.ACCOUNT
SET memb.ACCOUNT = (#acct:=#acct+1),
loan.ACCOUNT = (#acct);
This way you don't have to run the SELECT query at all, and you don't have to create a huge UPDATE statement with potentially thousands of WHEN clauses.
Demo: SQLFiddle

What is fastest way to update multiple columns in a table from data of another table where updating table column(s) are something?

I have these two queries which work, but they are slow as can be. What is faster, or rather fastest way of doing this?
method 1)
$query = "
UPDATE list_data_extra
INNER JOIN list_data
ON (list_data_extra.serial_no = list_data.serial_no)
SET
list_data_extra.id = list_data.id,
list_data_extra.cid = list_data.cid,
list_data_extra.first = list_data.first,
list_data_extra.last = list_data.last,
list_data_extra.tracking_number = list_data.tracking_number
WHERE list_data_extra.id='0' AND list_data_extra.cid='0'
";
method 2)
$query = "UPDATE list_data_extra
INNER JOIN list_data USING (serial_no)
SET list_data_extra.id = list_data.id,
list_data_extra.cid = list_data.cid,
list_data_extra.first = list_data.first,
list_data_extra.last = list_data.last,
list_data_extra.tracking_number = list_data.tracking_number
WHERE list_data_extra.id='0'
AND list_data_extra.cid='0'";
Not sure this other method would be faster:
method 3)
$query="SELECT * FROM list_data_extra WHERE id='0' AND cid='0'";
$result=mysql_query($query);
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
while($row=mysql_fetch_array($result)) {
$querytwo = mysql_fetch_array(mysql_query(
"SELECT id, cid, first, last, tracking_number
FROM list_data
WHERE serial_no='".$row['serial_no']."'"), MYSQL_ASSOC);
$querythree = "UPDATE list_data_extra
SET id='".$querytwo["id"]."', cid='".$querytwo["cid"]."',
first='".$querytwo["first"]."', last='".$querytwo["last"]."',
tracking_number='".$querytwo["tracking_number"]."'";
mysql_query($querythree);
}
}
Another thing i tried is this, which is building entire query then executing it all at once, which is a bit faster than above, but still slow as junk. the above is like 9 minutes per 1000 records and this here below is like 5 minutes per 1000.
method 4)
$query="SELECT * FROM list_data_extra WHERE id='0' AND cid='0'";
$result=mysql_query($query);
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
$id_loop = "";
$cid_loop = "";
$first_loop = "";
$last_loop = "";
$trackingnumber_loop = "";
$listids = "";
while($row=mysql_fetch_array($result)) {
$querytwo = mysql_fetch_array(mysql_query("SELECT id, cid, first, last, tracking_number FROM list_data WHERE serial_no='".$row['serial_no']."'"), MYSQL_ASSOC);
$id_loop .= "WHEN ".$row['listid']." THEN '".$querytwo["id"]."' ";
$cid_loop .= "WHEN ".$row['listid']." THEN '".$querytwo["cid"]."' ";
$first_loop .= "WHEN ".$row['listid']." THEN '".$querytwo["first"]."' ";
$last_loop .= "WHEN ".$row['listid']." THEN '".$querytwo["last"]."' ";
$trackingnumber_loop .= "WHEN ".$row['listid']." THEN '".$querytwo["tracking_number"]."' ";
$listids .= ", ".$row['listid'];
}
$listidsb = substr($listids, 2);
$querythree = "UPDATE list_data_extra
SET
id = CASE listid
".$id_loop."
END,
cid = CASE listid
".$cid_loop."
END,
first = CASE listid
".$first_loop."
END,
last = CASE listid
".$last_loop."
END,
tracking_number = CASE listid
".$trackingnumber_loop."
END
WHERE listid IN (".$listidsb.")";
mysql_query($querythree) or die(mysql_error());
}
Is there a better and faster way to update multiple columns in many records in one table with data from another table?
CREATE TABLE list_data (
id int(11) NOT NULL AUTO_INCREMENT,
cid int(11) NOT NULL,
first varchar(255) NOT NULL,
last varchar(255) NOT NULL,
tracking_number varchar(255) NOT NULL,
serial_no varchar(9) NOT NULL,
PRIMARY KEY (id)
) ENGINE=MyISAM AUTO_INCREMENT=555555 DEFAULT CHARSET=latin1
Unindexed JOIN and WHERE conditions can be slow, especially if they involve string data; try running these two (they make take a little time to run if the tables are large), and then trying your original query again.
ALTER TABLE list_data
ADD INDEX serial_idx (serial_no);
ALTER TABLE list_data_extra
ADD INDEX serial_idx (serial_no);

MySQL update table on vote script

I have a voting script on my message board. When somebody votes, it uses vote.php:
$check_query = " insert into m_votes set votes = {$vote_type}, ip = '$user_ip', messageid = $mid, name = '$name', messageby = '$mbu'";
$check_query_result = mysql_query($check_query) or die(mysql_error());
// return back total votes
$votes_query = "select sum(votes) as votes from m_votes where messageid = $mid";
$votes_query_result = mysql_query($votes_query) or die(mysql_error());
$votes_query_row = mysql_fetch_array($votes_query_result);
echo $votes_query_row['votes'];
// update score on guestbook_message table
$update = "UPDATE guestbook_message SET score = $votes_query";
The problem is with the last line of code. The 'score' field is on a different table to the one the votes information is held.I just want it so that when somebody votes on a message, it gets the sum of votes for that message, and updates the 'score' field on the guestbook_message table. But the code I have doesn't do this. it doesn't show a syntax error either.
$update = 'UPDATE guestbook_message SET score = ' . $votes_query_row['votes'];
mysql_query($update) or die(mysql_error());

if specific row = null, execute query

how do i check if the value of a column is null, and only then execute the query? for example:
col1 col2 col3
01 abc
i run a query which first checks if the record exists or not; if it exists, it should execute the update query and if it doesn't exist, it executes the insert query. how do i check if col3 is null and if it is null, it should execute the update query. .
$sql = "SELECT uid FROM `users` WHERE uid = '" . $user_id . "'";
$result = mysql_query($sql,$conn) or die('Error:' .mysql_error());
$totalrows = mysql_num_rows($result);
if($totalrows < 1)
{
insertUser($user_id,$sk, $conn);
}
else
{
updateSessionKey($user_id,$sk,$conn);
}
http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
Not really checking a value of the column, but I don't think you actually need that.
You need to have uid as a UNIQUE column. You try to insert a row for a new user with the given uid; if it finds the user with the same uid, then you do the update instead.
UPDATE:
I guess you did not bother to read the link.
I did not test it, but it should be something like this:
INSERT INTO users (uid, name, session)
VALUES ('login', 'Real Name', 'SeSsIoN_iD')
ON DUPLICATE KEY UPDATE session='SeSsIoN_iD'
This will insert the user if he does not exist, and if he does, it will set a new session key. OR, if you want to preserve the old session key if he already has one,
INSERT INTO users (uid, name, session)
VALUES ('login', 'Real Name', 'SeSsIoN_iD')
ON DUPLICATE KEY UPDATE session=IFNULL(session, 'SeSsIoN_iD')
One query, not three. You were not already doing it.
$sql = "SELECT * FROM `users` WHERE uid = '" . $user_id . "'";
$result = mysql_query($sql,$conn) or die('Error:' .mysql_error());
$totalrows = mysql_num_rows($result);
if($totalrows < 1)
{
$res = mysql_fetch_array($sql);
if(!empty($res['col3'])) {
insertUser($user_id,$sk, $conn);
}
}
else
{
updateSessionKey($user_id,$sk,$conn);
}
Is this what you mean?
If the record does not exist -> insert.
If the record does exist and its col3 is null -> update
If the record does exist, but its col3 is not null -> do nothing?
That could be achieved like this (untested):
$sql = "SELECT uid, col3 FROM `users` WHERE uid = '" . $user_id . "'";
$result = mysql_query($sql,$conn) or die('Error:' .mysql_error());
$totalrows = mysql_num_rows($result);
if($totalrows < 1)
{
insertUser($user_id,$sk, $conn);
}
else
{
$col3value = mysql_result($result, 0, 'col3');
if (is_null($col3value))
{
updateSessionKey($user_id,$sk,$conn);
}
}