MYSQL ON DUPLICATE KEY UPDATE not working as intended [duplicate] - mysql

This question already has answers here:
Insert into a MySQL table or update if exists
(12 answers)
Closed 2 years ago.
My app automatically checks when the customer logs in and only gives back one access_token and one shop values.
Below is the table with headings and a row of example data
access_token
shop
111111111
shop1
Sometimes a new customer installs the app and a new shop and access_token is created and I need to INSERT all new data in each column.
Other times the customer has re-installed the app so the shop exists but the access_token has changed and I need to update it.
How do I INSERT if none exist, but UPDATE if a value (shop) exists and another (access_token) doesn't when I am only given a single value of each?
I have attempted with ON DUPLICATE KEY UPDATE below where the shop is the same but the access_token has changed, but because I only get given one access_token to check when the customer logs in to the app it would just insert and not update.
INSERT INTO customers (access_token, shop)
VALUES(111, "shop1")
ON DUPLICATE KEY UPDATE access_token=111
I have attempted an example below where the shop is the same but the access_token has changed, however, I keep getting syntax errors. Please help, thank you.
SELECT EXISTS(SELECT shop FROM customers WHERE shop = 'shop1') AS sp,
NOT EXISTS (SELECT access_token FROM customers WHERE access_token = '{999999999}') AS tk
IF sp AND tk = 1
UPDATE customers
SET access_token='999999999'
WHERE shop = 'shop1';
ELSEIF NOT EXISTS (SELECT shop FROM customers WHERE shop = 'shop1') THEN
INSERT INTO customers (access_token, shop)
SELECT * FROM (SELECT '999999999', 'shop1') AS tmp;
END IF;

Are you using purely MySQL? I have made a signup and login page before as part of a web app and used Php to do this. I believe you can use Php for apks so I will write in Php, but you should be able to translate to your language with ease.
<?php
if (isset($_POST['signup-submit'])) { //this is so that the following can only be done on
the button press (name of it is signup-submit)
require 'dbh.inc.php';
$username = $_POST['Username'];
$email = $_POST['mail'];
$password = $_POST['pwd'];
$confirmpassword = $_POST['cpwd']; //this is all off the details of the user passed
through to be run through this script into the
database
if (empty($username) || empty($email) || empty($password) || empty($confirmpassword)) {
header("Location: ../index.php?error=emptyfields&uid=". $username. "&mail=". $email);
exit();
} //checking for empty fields
else if (!filter_var($email, FILTER_VALIDATE_EMAIL) && !preg_match("/^[a-zA-Z0-9 ]*$/", $username)) {
header("Location: ../index.php?error=invalidemail&uid");
exit();
}
else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: ../index.php?error=invalidemailuid");
exit();
}
else if (!preg_match("/^[a-zA-Z0-9 ]*$/", $username)) {
header("Location: ../index.php?error=invaliduid&email=". $email);
exit();
}
else if ($password !== $confirmpassword) {
header("Location: ../index.php?error=checkpasswords&mail=".$email. "&uid=".$username);
exit();
} //checking all characters used are only that which you allow
else {
$sql = "SELECT uidusers FROM users WHERE uidusers=?";
$sqly = "SELECT emailusers FROM users WHERE emailusers=?";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../index.php?error=sqlerror");
exit();
} //using prepared statements to insert user info
else {
mysqli_stmt_bind_param($stmt, "s", $username);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$resultCheck = mysqli_stmt_num_rows($stmt);
if ($resultCheck > 0) {
header("Location: ../index.php?error=usertaken&mail=". $email);
exit();
} //checking for existing details
if (!mysqli_stmt_prepare($stmt, $sqlx)) {
header("Location: ../index.php?error=sqlerror");
exit();
}
if (!mysqli_stmt_prepare($stmt, $sqly)) {
header("Location: ../index.php?error=sqlerror");
exit();
}
else {
mysqli_stmt_bind_param($stmt, "s", $email);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$resultCheck3 = mysqli_stmt_num_rows($stmt);
if ($resultCheck3 > 0) {
header("Location: ../index.php?error=emailtaken");
exit();
} //storing details
else {
$sql = "INSERT INTO users (uidusers, emailusers,
pwdusers, invcode) VALUES (?, ?, ?, ?) ";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../index.php?error=sqlerror");
exit();
}
else {
$hashedpwd = password_hash($password, PASSWORD_DEFAULT); //hashing passwords
mysqli_stmt_bind_param($stmt, "sss", $username, $email, $hashedpwd);
mysqli_stmt_execute($stmt);
header("Location: ../index.php?signup=success"); //all details stored successfully
As for your access token, I would suggest adding a function to run a uniqid() function along with another function to check for existing tokens so that duplicates aren't made ( I did this for another similar reason to yours) and then using similar code as above to write that in.
I'm not sure what your shop ID is for but I have options for 2 eventualities:
If it's just a sort of ID, auto increment it in the database
If it's to show which shop the person entered, use foreign keys to link the column to a parent table with all the shops listed and set the relationship to cascade. Then make a button to switch shops that will
A) send an update to the database, overwriting the child column and row of the user
B) redirect the user to the new shop
(I have no idea why the second half of the code is green, but if you remove my comments you should be good, though I'd advise you to write your own code so that you can see how it works and adapt it to your own project)

Related

MYSQL DELETE INNER JOIN only shows deletes after page reload

I have managed to get working a Duplicate field Check using INNER JOIN with PHP MYSQL , however the delete only shows after a page reload , the 1st time i load the page the duplicate entry's are shown then i reload the page and the DELETES are no longer showing. i dont understand why, does this code show any reason for this to happen? a page refresh does not happen no matter what code i use, nothing is run during the IF ($RowsDC >1) check other than the DELETE statement
here is the code:
while($row = $stat->fetch()){
//checking for duplicates
try {
$db2 = new PDO("mysql:host=localhost;dbname=classifieds2", 'root', ''); // 1. set database with this instead of conect - or change conect to this
$db2->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$queryDC="SELECT * FROM listings WHERE listID = ? AND UID = ? ";
$statDC=$db2->prepare($queryDC);
$statDC->execute(array("$listID","$UID"));
$ResultDC = $statDC->fetchAll();
$RowsDC = count($ResultDC);
if ($RowsDC >1){ $db2A = new PDO("mysql:host=localhost;dbname=classifieds2", 'root', ''); // 1. set database with this instead of conect - or change conect to this
$db2A->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query01DC="DELETE a FROM listings a INNER JOIN listings a2 WHERE a.id < a2.id AND a.listID = a2.listID ";
$stat01DC=$db2A->prepare($query01DC);
$stat01DC->execute();
??? here i have tried to refresh the page but it does not no matter how i try nothing is run ???
}
}
catch (PDOException $e){
$_SESSION['message']="Database Error #vbmDUPCHECK2 <br> <h6><h6>Signed Out For Security Reasons</h6></h6>";
$_SESSION['loggedin']='000';
echo $errorcall;
die();
exit();
}
}//WHILE END

Why am i unable to insert a data in to data base

These are the codes for the page:
<?php
session_start();
if(isset($_SESSION['level'])){
if($_SESSION['level'] == 2 ){
require("../db/dbConn.php");
$submitted = isset($_POST['submit']);
if($submitted){
//check user's input
if(isset($_POST['issue_type'])){
$issue_type =$_POST['issue_type'];
}
else {
$issue_type = null;
echo '<p><font color="red">Please Select a Issue Type</font></p>';
}
if(isset($_POST['description'])){
$description=$_POST['description'];
}
else{
$description = null;
echo '<p><font color="red">You forgot to enter a description</font> </p>';
}
if(isset($_POST['reported_account_id'])){
$reported_account_id = $_POST['reported_account_id'];
}
else{
$reported_account_id = null;
echo '<p><font color="red">You forgot to enter your ID</font></p>';
}
if(isset($_POST['DateTimeCreated'])){
$DateTimeCreated=$_POST['DateTimeCreated'];
}
else{
$DateTimeCreated= null;
echo '<p><font color="red">You forgot to enter the date and time of the Issue </font></p>';
}
//Prepare the Insert Statement
$stmt = "INSERT INTO problem (issue_id, description, reported_account_id, DateTimeCreated) VALUES ('$issue_type', '$description','$reported_account_id','$DateTimeCreated')";
$result = mysqli_query($conn, $stmt);
$conn->close();
//TODO 5: Check result of executing insert statement and rows inserted. Print user's input if 1 row is inserted successfully,
// else print error message
if($result==true){
echo '<p><font color="green">The problem has been created. Thank you</font></p>';
echo '<p>Registration Successful Please Click Here';
} else {
echo "<p><font color=red><b>Data not saved. Please try again</b></font></p>";
echo '<p>Inserting Failed Please Click Here to Try Again';
}
}}
} else {
header("Location: ../index.php");
}
?>
I am not able to submit the insert the details from the form page into the database. That is the only issue that i am faced with. Please help me point out the errors that i made.
To Fix the issue, please replace
$stmt = "INSERT INTO problem (issue_id, description, reported_account_id, DateTimeCreated) VALUES ('$issue_type', '$description','$reported_account_id','$DateTimeCreated')";
With
$stmt = "INSERT INTO problem (issue_id, description, reported_account_id, DateTimeCreated) VALUES ('"+$issue_type+"', '"+$description+"','"+$reported_account_id+"','"+$DateTimeCreated+"')";

delete user from table

I have this table where I want to delete user from. The users are in my database "login" where they have an id, username and password.
"Id" is the primary key, I want to delete the user where I click in my table
Hope you can help me out!
<?php
$account = '<font size="4">'.$account.'</font>';
$password1 = 'Password:';
$password1 = '<font size="4">'.$password1.'</font>';
//check db connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Take everything from table and fill in $result
$sql = "SELECT * FROM login";
$result = $conn->query($sql);
echo"<table border=4><tr><td>$account</td><td>$password1</td><td>Action</td></tr>";
if ($result->num_rows > 0) {
// Take all data
while($row = $result->fetch_assoc()) {
echo"<tr><td>".$row['username']."</td><td>".$row['password']."</td><td> edit | delete </td></tr>";
}
} else {
// nothing in DB is 0 results
echo "0 results";
}
echo"</table>";
$conn->close();
?>
<td> edit | <a href='baseURL/deleteUser.php&id=$userId'> delete</a> </td></tr>";
create a page deleteuser.php, get the id via $_GET['id'] and delete accordingly.
This is a very crude approach to delete users and the id goes via browser url. You can add forms here and delete text can be a submit button .. The id can be sent as hidden and obtained via $_POST

mysql_num_rows comparison operator

Edit Note: There was nothing wrong with this comparison operator. I was asked to expound, so added the code below. As it turned out, the problem was in the UniqueID function I was using to create a unique string.
I'm trying to troubleshoot an intermittent problem in a database save. Basically, the code does an earlier query with posted data. I then check the number of rows in that query to determine whether to update or insert the record.
About 1% of the time, this doesn't work, and an unrelated record is overwritten. I'm wondering if, perhaps there is something wrong with the comparison operator I am using with mysql_num_rows().
Are there any possible odd effect with using
if(mysql_num_rows($Result) != 0)
ADDED LATER:
mysql version 5.0.51a
I will try my best to explain what is important here.
The tables are involved in an in-house credit application. The salesperson fills out a form for the company applying for the credit. They can then save that application to complete later or send off to the accounting dept for approval. The accountant can save the record for later, return it to the salesperson, or approve it. In any of these operations the entire form is either inserted (when first created) or updated in the table record.
When any operations that transfer the access to the form to the salesperson or accountant, an e-mail is sent to the appropriate party, which includes a link to the record. The salesperson only has access to the records they have created. This is done by simply checking their login username, held in a session variable, with a field in the table that also holds their username.
At the top of the form is a select box that holds records waiting to be processed. What is available for the salesperson in that box is records he/she has stored or records sent back to him/her for corrections and re-submission. They can pull up a form by simply selecting one. They can also retrieve a form by clicking on the e-mail link, sent to them when they submit a form or the admin (accountant) returns a form to them. Likewise, the accountant can do the same, by both methods, with records sent to them to process.
Each transaction in this process in logged in a Transaction Detail Table.
There are many error checks that prevent a record from being accessed inappropriately. (Bear with me, this is all important) Salesperson and Accountant do not have access to the record at the same time and, once an application is approved, neither have access except to view.
The Problem
Everything is dependent on the ID field, which is an auto-increment mysql field in the CreditApp table. This number is stored in the log file in the "AppID" field. In about 1% of these transactions, either when the salesperson submits the form to the admin (accountant) or the accountant approves it, rather than updating the correct record, a completely unrelated record is updated. Each overwritten record is a record that has been previously processed (meaning "approved" by the accountant). Very often, but not necessarily, the record that is overwritten can be a year or two old.
Although I'm not sure whether the record is overwritten on submit by the salesperson or on approval by the admin, the other peculiar thing is that, when this overwrite happens, the entries in the log table, on submit by the salesperson, do not have the AppID that relates them to the form record. It is blank.
So here is a very simplified mock up of the process (I am sure there is a much more eloquent way to do this but alas...):
if($Process == "RegularSave") // Salesperson storing record for later
{
$Status = "Store";
$StoreTitle = $NewTitle;
if(empty($StoreTitle)){$Error[] = "Title cannot be blank. Record was not saved!";}
$Q = "SELECT ID, StoreTitle FROM CreditApp WHERE ID = '$ID' OR UniqueID = '$UniqueID'"; // UniqueID prevents double entry on refresh of new record
$Result = mysql_query($Q);
if(!$Result){$Error[] = "Database error in storage result!";}
}
elseif($Process == "RegularSubmit") //Sslesperson submitting record
{
$Status = "Received";
$StoreTitle = $NewTitle;
if(empty($StoreTitle)){$Error[] = "Title cannot be blank. Record was not saved!";}
$Q = "SELECT ID FROM CreditApp WHERE ID = '$ID' OR UniqueID = '$UniqueID'"; // UniqueID prevents double entry on refresh of new record
$Result = mysql_query($Q);
if(!$Result){$Error[] = "Database error in ID Check!";}
}
elseif($Process == "AdminProcess" || $Process == "AdminSave" || $Process == "AdminReturn")
{
// Status variable set here as to "Revised", "Rejected", "Approved", etc.
// THEN:
$Q = "SELECT ID FROM CreditApp WHERE ID = '$ID'";
$Result = mysql_query($Q);
if(!$Result){$Error[] = "Database error in ID Check!";}
}
elseif($Process == "AdminSend")
{
// Setup for e-mail from admin when returning record for corrections
$ReturnDate = dFormat($Time,41);
$FromName = $AdminName;
$FromEmail = $AdminAddress;
$ReturnUser = $_SESSION['FullName'];
$DetailMsg = nl2br($Message);
$NoteString = '======================='."\n".$ReturnUser.': '.$Today."\n".$Message."\n".'======================='."\n".$Notes;
$R = mysql_query("UPDATE CreditApp SET Notes = '$NoteString', Status = 'Return', ReturnDate = '$ReturnDate', ReturnUser = '$ReturnUser', AdminID = '$_SESSION[User]' WHERE ID = '$ID'");
$M = mysql_query("INSERT INTO CustAcctStatsDetail (AppID,Action,Detail,Form,TranUser) VALUES ('$ID','Return for Corrections','$DetailMsg','$FormName','$_SESSION[User]')");
$HTMLData = ('Your credit request for '.$AcctName.' has been returned for the following reasons:<br /><br />'.nl2br($Message).'<br /><br />
FormLink: You can access the record from this link.<br />
You will also find it available in your stored records list at the top of the Credit Application Request form.
<br /><br />');
}
if(count($Error) == 0 && $Process != "AdminSend")
{
if(mysql_num_rows($Result) != 0) // Indicates record already exists
{
#=====================================================#
# Update Existing Record #
#=====================================================#
$X = mysql_fetch_array($Result);
$Q = "UPDATE CreditApp ... WHERE ID = '$X[ID]'"; // Standard Update set of fields
$Result = mysql_query($Q);
if(!$Result){$Error[] = "Database update error! (1) ApproveDate: ".$ApproveDate.' '.mysql_error();}
else
{
// Here related tables are updated (simple one-to-many relationships for form data)
// THEN:
#=====================================================#
# Log any changes #
#=====================================================#
$LQ = "UPDATE CustAcctStats SET StoreTitle = '$StoreTitle', Company = '$AcctName',";
if($AppType == "New"){$ApprovalString = $Approval;}
elseif($Approval == "Approved"){$ApprovalString = "Completed";} // Revised entry
else{$ApprovalString = $Approval;}
if($_SESSION[GVars][Approval] != $Approval || $AppType == "Revised")
{
$StatusString = $Status.'/Credit';
$LQ .= " Status = '$StatusString', CreditApproval = '$ApprovalString', CreditDate = '$ThisDate',";
}
$TAction=array(); $TDetail=array();
if($_SESSION[GVars][SubmitDate] != $SubmitDate)
{
$TAction[] = 'Form Submitted';
$TDetail[] = $AppType != "Revision" ? "Credit Application submitted for approval" : "Credit Revision Request submitted";
$LQ .= " SubmitDate = '$SubmitDate'";
}
if($_SESSION[GVars][Approval] != $Approval || $_SESSION[GVars][SubmitDate] != $SubmitDate || $AppType == "Revised")
{
if(substr($LQ,-1) == ','){$LQ = substr($LQ,0,-1);}
$LQ .= " WHERE AppID = '$ID'";
$Result = mysql_query($LQ);
if(!$Result){$Error[] = "Log File Error! [1] ".mysql_error();}
}
if($_SESSION[GVars][Approval] != $Approval || $AppType == "Revised")
{
if($AppType != "Revised")
{
if($Approval == "Approved")
{
$TAction[] = '<span class="LogBlue">Credit Application Approved</span>'; $TDetail[] = 'This Credit Application has been approved for '.$CreditAmt;
}
elseif($Approval == "Declined")
{
$TAction[] = '<span class="LogRed">Credit Application Declined</span>'; $TDetail[] = 'This Credit Application has been declined';
}
}
else
{
if($Approval == "Approved")
{
$TAction[] = '<span class="LogBlue">Credit Revision Approved</span>'; $TDetail[] = 'This submitted credit revision has been approved and completed.';
}
elseif($Approval == "Rejected")
{
$TAction[] = '<span class="LogRed">Credit Revision Rejected</span>'; $TDetail[] = 'This Credit Revision has been rejected';
}
}
}
if($_SESSION[GVars][Status] != $Status)
{
$TAction[] = 'Status Change';
if(!empty($_SESSION[GVars][Status]))
{
$TDetail[] = 'Status change from '.$_SESSION[GVars][Status].' to '.$Status;
}
else
{
$TDetail[] = 'Status change set to '.$Status;
}
}
if($_SESSION[GVars][StoreTitle] != $StoreTitle)
{
$TAction[] = 'Store Title Change';
if(empty($_SESSION[GVars][StoreTitle]))
{
$TDetail[] = 'Store Title created: '.$StoreTitle;
}
else
{
$TDetail[] = 'Store Title change from '.$_SESSION[GVars][StoreTitle].' to '.$StoreTitle;
}
}
$TranCount = count($TAction);
for($a=0;$a<$TranCount;$a++)
{
$Q = "INSERT INTO CustAcctStatsDetail (AppID,Action,Detail,Form,TranUser) VALUES ('$ID','$TAction[$a]','$TDetail[$a]','$FormName','$_SESSION[FullName]')";
$Result = mysql_query($Q);
if(!$Result){$Error[] = "Log File Error! [2]";}
if($Status == "Processed")
{
$Q = "UPDATE CustAcctStats SET StoreTitle = '$StoreTitle', Company = '$AcctName', CreditDate = CURDATE(), Date = NOW(), AdminUser = '$_SESSION[User]' WHERE AppID = '$ID'";
}
else
{
$Q = "UPDATE CustAcctStats SET StoreTitle = '$StoreTitle', Company = '$AcctName', Date = NOW() WHERE AppID = '$ID'";
}
$Result = mysql_query($Q);
}
switch($Process)
{
// Text is set here to display result and status to the user
}
}
}
elseif(!$_SESSION['Admin']) // Record is new entry. Admin only deals with records in process
{
#=====================================================#
# Create New Record #
#=====================================================#
$Q = "INSERT INTO CreditApp ..."; // Standard Insert set of fields
$Result = mysql_query($Q);
if(!$Result){$Error[] = "Error in database insert! (1) ".mysql_error($Conn);}
else
{
// Here related tables are updated (simple one-to-many relationships for form data)
// THEN:
#=====================================================#
# Create new Log Entry #
#=====================================================#
$CreditApproval = !empty($Approval) ? $Approval : "";
if(!empty($ApproveDate)){$CreditDate = $ApproveDate;}
if(!empty($DeclineDate)){$CreditDate = $DeclineDate;}
if($Process == "RegularSave")
{
if($AppType != "Revision")
{
$Action = "Record Created";
$Detail = "A new record was created but stored to submit at a later date.";
$StatusString = "Store/Credit";
}
else
{
$CreditApproval = "Current";
$Action = "Credit Revision";
$Detail = "A Credit Revision was created but stored to submit at a later date.";
$StatusString = "Store/Credit";
}
}
elseif($Process == "RegularSubmit")
{
if($AppType != "Revision")
{
$Action = "Record Created";
$Detail = "A new record was created and sent to Administration for approval.";
$StatusString = "Received/Credit";
}
else
{
$CreditApproval = "Current";
$Action = "Credit Revision";
$Detail = "A Credit Revision was sent to Administration.";
$StatusString = "Received/Credit";
}
}
else
{
$Action = "Error!";
if(empty($Process)) // "Detail text added 2/19/15 (Previously was blank)
{
$Detail = "Process variable is empty";
}
else
{
$Detail = $Process.' should equal RegularSave or RegularSubmit';
}
}
if(empty($CreditDate)){$CreditDate = "0000-00-00";}
if(empty($SubmitDate)){$SubmitDate = "0000-00-00";}
$Result = mysql_query("INSERT INTO CustAcctStats (AppID,AppType,User,StoreTitle,Company,Status,CreditApproval,CreditDate,SubmitDate,Date)
Values ('$ID','$AppType','$_SESSION[User]','$StoreTitle','$AcctName','$StatusString','$CreditApproval','$CreditDate','$SubmitDate',NOW())");
if(!$Result){$Error[] = "Log File Error! [3] ".mysql_error();}
else
{
$Result = mysql_query("INSERT INTO CustAcctStatsDetail (AppID,Action,Detail,Form,TranUser,TranDate) VALUES ('$ID','$Action','$Detail','$FormName','$_SESSION[FullName]',NOW())");
if(!$Result){$Error[] = "Log File Error! [4]";}
}
}
}
elseif($_SESSION['Admin'])
{
$Error[] = "Record not found!<br />Please exit Admin mode if you want to save a new record!";
}
}
if(($_POST['Submit'] == "Submit" || $Process == "AdminSend" || $Process == "AdminProcess") && count($Error) == 0)
{
// Here the e-mail is generated
}
You are using InnoDB, correct? And you have multiple connections possibly doing queries like this? But you don't don't have BEGIN...COMMIT around the pair (SELECT, INSERT/UPDATE) of statements?
Switch to INSERT ... ON DUPLICATE KEY UPDATE ... in order to do the process in a single, atomic, operation.
If you do have BEGIN...COMMIT, does the SELECT have FOR UPDATE on the end? It should -- in order to lock the record that needs UPDATEing or lock the spot where the new record will be INSERTed.
SELECT ID, StoreTitle FROM CreditApp WHERE ID = '$ID' OR UniqueID = '$UniqueID'
That probably performs very slowly. Check the EXPLAIN or time it. The workaround is to turn it into a UNION:
( SELECT ID, StoreTitle CreditApp WHERE ID = '$ID' )
UNION DISTINCT
( SELECT ID, StoreTitle CreditApp WHERE UniqueID ='$UniqueID' )
I don't see where $R (the INSERT?) or $M (the UPDATE?) are being executed. How long does it take between the SELECT and the INSERT/UPDATE? The longer that timespan, the more chance of another connection slipping in.
Furthermore if that OR is slow, you could have multiple SELECTs queued up, waiting to sneak in. And a SELECT without an OR can slip in very fast.
As I understand it, you really need the LOCK TABLES WRITE... before the SELECT and UNLOCK TABLES after the INSERT/UPDATE. Otherwise, as you have seen, occasionally, things mess up.
Or, skip the LOCK/UNLOCK and turn the INSERT/UPDATE into INSERT...ON DUPLICATE KEY UPDATE, since it is atomic. (Even if the SELECT is kept, and even if it goofs, the IODKU will correct for it.)

MySQL Query not updating database

Perhaps I am just being a complete idiot but I am trying to insert a record into a MySQL table but it doesn't seem to be working. When I test it (i.e. get the script to echo the values so I can check that they are being posted by the form), they are being sent but the query isn't posting to the database. Like I said, perhaps I am being a complete idiot but I felt that perhaps a fresh set of eyes might speed up my troubleshooting because I have been fighting with this issue for the past 2 hours!
Here is the code:
// Connects to your Database
mysql_connect("localhost", "dbuser", "dbpword") or die(mysql_error());
mysql_select_db("dbname") or die(mysql_error());
// Get Variables
$sectorid = $_POST['sectorid'];
$parentid = $_POST['parentid'];
$sectorname = $_POST['sectorname'];
$status = $_POST['status'];
$creon = $_POST['creon'];
$creby = $_POST['creby'];
$modon = $_POST['modon'];
$modby = $_POST['modby'];
//Insert Record
mysql_query("INSERT INTO cand_emp_sector (sectorid, parentid, sectorname, status, creon, creby, modon, modby)
VALUES ('$sectorid', '$parentid', '$sectorname', '$status', '$creon', '$creby', '$modon', '$modby)");
//On completion, redirect to next page
header("Location: canddb.new.7i.php");
Any assistance would be greatly appreciated.
Thanks
you are missing a quote at the end
, '$modby')");
^---------here
Check the result for errors:
$result = mysql_query("INSERT INTO cand_emp_sector (sectorid, parentid, sectorname, status, creon, creby, modon, modby)
VALUES ('$sectorid', '$parentid', '$sectorname', '$status', '$creon', '$creby', '$modon', '$modby)");
if($result === false) die('query failed..');