SQL query adding a duplicate rows on every run in php - php

Below piece of code on every execution is creating two rows. Just for testing purpose I commented out php variables and replace them with hardcoded value like '1', '3' etc in VALUE clause of INSERT query. I could not find out the exact cause, so putting here the entire code. Here TaskID is Auto incremented column.
/* CONNECT TO DATABASE TO ADD THIS TASK IN PT_TASK TABLE */
if ($ConnectStatus) {
echo '1';
$Query = "INSERT INTO PT_TASKS (TaskID, ParentID, Title, AssignedTo, Category, Status, Zone, Created, CreatedTime, LastModified, ProgressPercent, Notes, StartDate, TargetDate, ActualStart, ActualEnd)
VALUES (' ','12449','3','1','1','1','1','1','1','1','1','1','1','1','1','1')";
// VALUES (' ','$ParentID','$Title','$AssignedTo','$Categories','$Status','$Zone','$Created','$CreatedTime','$LastModified','$ProgressPercent','$Notes','$PlannedStart','$PlannedEnd','$ActualStart','$ActualEnd')";
if (!mysql_query($Query,$con))
{
die('Error: ' . mysql_error());
}
else
{
echo "updated1";
}
$Query_result = mysql_query($Query);
}
else {
?><div class="Error">Database Connection Failed. Can not create this project. </div><?php
}
Whenever I refresh this page two rows get added in table PT_TASKS. Ideally only one row should get added in PT_TASKS. Not sure what mistake I am making. Please help.

Take out the last
$Query_result = mysql_query($Query);
Since you are already executing the query before that as
if (!mysql_query($Query,$con))

Related

Insert operation based on conditions in mysql php

I am stuck at a position where I need to do an insert operation for 'n' number of chapters on one submit button and through one insert query basically in a loop.
Now my question is if a user has passed exam for chapter number 3, then I don't want to insert record for chapter 3. Is this achievable? I've tried to solve this myself but couldn't find a way.
Here is my code:
for($i = 1; $i=5; $i++) {
$sql="INSERT INTO tbl_user_reattempt (ID,user_id,chapter_id,days_for _start,days_for_end,created) VALUES ('','$user_id','$chapter_id','$days_for_start','$days_for_end','$created')";
$result = mysql_query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
}
What modifications has to be done?
Create unique index for 2 fields: user_id and chapter_id.
Use ON DUPLICATE KEY UPDATE ID = ID in the end of your INSERT query.

Using On Duplicate Key Update with an array

I'm relatively new to MYSQL and am having trouble combining idea I have read about. I have a form generated from a query. I want to be able to insert or update depending on whether there is currently a matching row. I have the following code which works for inserting but I;m struggling with the On DUPLICATE UPDATE part I keep getting a message saying there is an error in my syntax or unexpeted ON depending on how I put the ' .
require_once("connect_db.php");
$row_data = array();
foreach($_POST['attendancerecordid'] as $row=>$attendancerecordid) {
$attendancerecordid=mysqli_real_escape_string($dbc,$attendancerecordid);
$employeeid=mysqli_real_escape_string($dbc,($_POST['employeeid'][$row]));
$linemanagerid=mysqli_real_escape_string($dbc,($_POST['linemanagerid'][$row]));
$abscencecode=mysqli_real_escape_string($dbc,($_POST['abscencecode'][$row]));
$date=mysqli_real_escape_string($dbc,($_POST['date'][$row]));
$row_data[] = "('$attendancerecordid', '$employeeid', '$linemanagerid', '$abscencecode', '$date')";
}
if (!empty($row_data)) {
$sql = 'INSERT INTO attendance (attendancerecord, employeeid, linemanagerid, abscencecode, date) VALUES '.implode(',', $row_data)
ON DUPLICATE KEY UPDATE abscencecode = $row_data[abscencecode];
echo $sql;
$result = mysqli_query ($dbc, $sql) or die(mysqli_error ($dbc));
}
The various echo statements are showing that the correct data is coming through and my select statement was as expected before I added in the ON DUPLICATE statement.
You need to fix the way the sql statement is constructed via string concatenation. When you create an sql statement, echo it and run it in your favourite mysql manager app for testing.
$sql = 'INSERT INTO attendance (attendancerecord, employeeid, linemanagerid, abscencecode, date) VALUES ('.implode(',', $row_data).') ON DUPLICATE KEY UPDATE abscencecode = 1'; //1 is a fixed value yiu choose
UPDATE: Just noticed that your $row_data array does not have named keys, it just contains the entire new rows values as string. Since you do bulk insert (multiple rows inserted in 1 statement), you have to provide a single absencecode in the on duplicate key clause, or you have to execute each row in a separate insert to get the absence code for each row in a loop.

Same Auto Incremental ID Should be insert into Insert Query

I need some help from you people. I don't know It's possible or not.
In PHP, When I insert new query into Database ID value will be auto increment. I have one more variable in that Query, which is parentID.
When Run the query, parentID should be equal to the auto Incremental ID.
I tried mysqli_insert_id($conn); this function. Get last ID. Add one with that value then assign that value to parentID and then insert into database.
But Some kind of time it may be give Isolate problem. So any one guide to provide some other solution to avoid Isolate problem. Isolate means when I try to insert, I got last ID from db. Now assign that value to ParendID variable. And then I try to insert Into DB. Assume it may take few minutes. Within that few minutes some other guys may insert their own regards. That time my last ID will be differed. So I Insert with wrong parendID value.
Please any one help me to solve this problem..!!
<?php
//My connection
$last_id = $conn->insert_id; //get last ID from DB
$parent_id = $last_id + 1;
$sql = "INSERT INTO MyGuests (firstname, lastname, email, ParentID)
VALUES ('John', 'Doe', 'john#example.com', $parent_id)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully.";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
First I get LastID and then add One with that value. Then I'll insert Into DB. Instead of this method, In query itself, Directly, can give any other possible solution to assign parent ID equal to current ID of the field?
This can be done with the help of the triggers,
all you need to do is copy the new value of the id into the parentID "AFTER" insertion.
CREATE TRIGGER ins_parentID
AFTER INSERT ON MyGuests
FOR EACH ROW SET
NEW.ParentId = NEW.ID;
Code should look something like this (THIS ONE IS NOT TESTED)

PHP MySQL PDO duplicates

I have the below code, which works perfect. What i want to do is to check the refNo first to see if there are duplicates entries in MySQL. If there is then appear a warning message, otherwise appear a "ok" message. How can i do that with PDO? Any help?
(include("db.php"));
$SQLquery = "INSERT INTO mydatabase (refNo, name)
VALUES ('".$_POST["refNo"]."', '".$_POST["name"]."');";
$STH = $dbc->query($SQLquery);
?>
edit: Hello guys,
i prefer not to add primary keys. Is there any other way?
Set up refNo as a primary key. You could also create it as unique but that defeats the purpose - your reference number appears to be a unique primary identifier. Perfect choice for a primary key.
Further, change your query
try {
$SQLquery = "INSERT INTO mydatabase (refNo, name) VALUES (:refNo, :name)";
$SQLquery = $dbc->prepare($SQLquery);
$SQLquery->bindValue(':refNo', $_POST['refNo']);
$SQLquery->bindValue(':name', $_POST['name']);
$SQLquery->execute();
} catch (Exception $e) {
die("Insert error");
}
$count = $SQLquery->rowCount();
if ($count == 1) {
echo "Record added!";
}
This binds the post value to prevent SQL injection too.
Edit: You could follow this up with $count = $SQLquery->rowCount(); which will be 1 if the insert was successful, as it appears you've edited your question since you posted it for more info.
If you want to do this without using a database level constraint, you'll need to do an extra SELECT statement before inserting into the table. But that gives you no absolute guarantees, as it might be two processes want to insert the same row at the same time and they will still succeed.
-- it'll look a little something like this; I'm not familiar with PDO but the structure should be the same
$selectQuery = "SELECT * FROM mydatabase
WHERE refno = '".$_POST["refNo"]."'";
$res = $dbc->query( $selectQuery );
if( $res->count() > 0 ) {
// this result already exists; show error
}
else {
// this result is new; put the insert query here
}

MySQL DELETE failing randomly and very infrequently

I have a MySQL DELETE statement followed by an INSERT statement to ensure only one copy of a data set for a given ID. (There is a reason why I do not use UPDATE)
The problem is that I have noticed in a data set spanning 5000+ entries that there are 3 instances where the DELETE statement did not execute, but the INSERT statement did. The end result was duplicate entries for the given IDs.
Below is my code. On execution failure the php script will exit with an error message. It must be my level of experience. Any ideas what the problem could be?
//delete
$query_delete = "DELETE FROM q1_6_list WHERE q_id = '".mysql_real_escape_string($q[qID])."'";
$result = mysql_query($query_delete) or errorReport("Error in query: $query_delete. ".mysql_error());
//insert
$query_insert = "INSERT INTO q1_6_list (q_id, vehicle, quantity) VALUES";
$result = mysql_query($query_insert) or errorReport("Error in query: $query_insert. ".mysql_error());
if (!$result)
errorReport($result);
EDIT
On closer inspection I noticed that I did not add the below code right after $result = mysql_query($query_delete)....
if (!$result)
errorReport($result);
Could this also be required to catch all other error messages, or would mysql_query($query_delete) or errorReport... catch all error occurrences?
Your best bet here is to create a primary key on q1_6_list (q_id):
ALTER TABLE q1_6_list ADD PRIMARY KEY(q_id)
and use MySQLs REPLACE INTO syntax, so lose your delete and your insert becomes:
$query_insert = "REPLACE INTO q1_6_list (q_id, vehicle, quantity) VALUES";
You could simply run insert query only if delete query was successful:
if (mysql_query($query_delete)) {
mysql_query($query_insert);
}

Categories