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
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+"')";
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
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.)
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..');