I have a DB with a unique number and a badge number. the badge number will change but the unique number wont.
|unique_number|badge_number|
|-------------|------------|
|1234 |2 |
|-------------|------------|
I want to be able to update badge_number in relation to unique_number without creating a new row (un-checking the key "unique"). But currently I get the error Error: Duplicate entry '1234' for key 'unique_number'
if I post this code:
$sql="INSERT INTO table (unique_number, badge_number) VALUES ('1234', 1)";
I have tried this:
$sql="INSERT INTO push (unique_number) VALUES ('".$_POST['unique_number']."')";
$sql2="UPDATE table set badge_number= 0 where unique_number=".$_POST['unique_number']."";
if (!mysqli_query($con,$sql))
{
echo'Error: ' . mysqli_error($con);
}
if (!mysqli_query($con,$sql2))
{
die('Error2: ' . mysqli_error($con));
}
If you make a primary key or a unique constraint applied to a column, any insertion of new data must verify the uniqueness of data based on that column. So I guess you have a constraint applied to the unique_numberColumn.
But you still change Data of an exesting row if and only if you the new data verify existing data.
UPDATE table SET badge_number = 1 WHERE unique_number = '1234'
INSERT queries are responsible to insert new records in table.
Hence if you are trying to insert a new row with unique_number=1234, it is violating unique key constraint and generates error Error: Duplicate entry '1234' for key 'unique_number' as there is already a record with this unique_number=1234.
If you want to update the existing record, you can use update query to update any record.
So if you need to update record where unique_number=1234, you need to use following query:
UPDATE table_name SET badge_number = 3 WHERE unique_number = 1234
Something like the following?
$sql = "UPDATE table SET badge_number = '0' WHERE unique_number = '$_POST['unique_number']'";
Related
Is there a way to auto-increment in MYSQL after deleting a row from the database?
For example:
There is a table with 3 columns: StudentID, Student Name, and Contact details. Here StudentID will be the primary key which will keep incrementing after adding values in each column.
The PHP code will look as follows:
<?php
require_once "Delete_Form.php";
if ($_GET || id['id']) {
$id = mysqli_real_escape_string($db, $_GET['id']);
} else {
echo 'Value was not brought over';
}
echo $id;
$result = mysqli_query($db,"SELECT StudentID, StudentName, Contact FROM student WHERE
StudentID='$id'");
$row = mysqli_fetch_row($result);
$sql= "DELETE FROM `student` WHERE `student`.`studentID` = $id";
echo "<pre>\n$sql\n</pre>\n";
mysqli_query($db,$sql);
echo 'Success -Continue...';
return;
Once we delete an entry from the database the Auto-Incrementation of StudentID will mess up i.e if the last entry had a StudentID of 12 and then we delete the same then the next row we enter will have StudentID of 13.
We can always do ALTER TABLE `student` AUTO_INCREMENT = 1 which will reset it but that will solve the problem temporarily only.
Is there a way to add a PHP statement in the above code to reset auto increment whenever we delete a row?
Do it never.
Primary key in a table identifies the row uniquely during the whole table lifetime. Pay attention - TABLE lifetime, not ROW lifetime. The fact that the row was deleted changes nothing - the value identifies this deleted row nevertheless.
If you need rows enumeration without the gaps then create special column for this purposes or enumerate in a query.
PS. By the way, synthetic AI PK must be hidden for the user at all - this column destination is row identifying and foreign keys subsystem work. It must not have any additional meaning.
I am using this http://www.phpzag.com/create-live-editable-table-with-jquery-php-and-mysql/ as a template for editing two columns in my table. The edited entries are saved in new SQL table and called by unique key identifier back.
With each edit where the ID does not exist in the SQL I need the ID to be created so instead just UPDATE:
UPDATE notes SET $update_field WHERE shop_order='" . $input["SHOP_ORDER_NO"] . "'"
statement in SQL I want to check if ID exist and if so, to just update edited value otherwise create ID and update value. The update statement above works when ID is created.
Code below update just the "priority" value, not the note when edited. Also when I edit "note" it will not create new ID. I tried to figure it out for half a day without success.
<?php
include_once("db_connect.php");
$input = filter_input_array(INPUT_POST);
$poznamka = $input['note'];
if ($input['action'] == 'edit') {
$update_field='';
if(isset($input["priority"])) {
$update_field.= "priority='".$input["priority"]."'";
} else if(isset($input["note"])) {
$update_field.= "note='".$input["note"]."'";
}
if($update_field && $input["SHOP_ORDER_NO"]) {
$sql_query = "INSERT INTO notes (shop_order,priority,note)
VALUES ('" . $input["SHOP_ORDER_NO"] . "','" . $input["priority"] . "','" . $input["note"] . "')
ON DUPLICATE KEY UPDATE $update_field ";
mysqli_query($conn, $sql_query) or die("database error:".mysqli_error($conn));
}
}
?>
That link is missing some things, like a PRIMARY KEY. And IODKU depends on a UNIQUE key, which is usually a different column.
Your statement will act on only row, assuming there is only one duplicate value for some UNIQUE key. Please provide SHOW CREATE TABLE and the generated SQL so we can point out specifics.
Read the online docs about using ... UPDATE id = LAST_INSERT_ID(id) as a kludge for getting the new or old auto_increment id.
If you need to apply IODKU to multiple rows, see the syntax
INSERT INTO t (col1, col2, ...)
ON DUPLICATE KEY UPDATE ...
SELECT ((multiple rows from somewhere else));
However, this cannot provide the auto_increment ids for each new/existing row.
Im creating a website for booking activities. I have 3 centres. The customer is cant book the same activity twice neither in a different centre. Im using a table in mysql which i store the infos provided by the costumers. Is there any way to filter or to check in my php code if a customer has already booked the same activity more than one time and echo an error msg?
my table(and the info im asking) contains these columns:
ID(Primary)
FirstName
LastName
Email
ContactNumber
ClassName
Week
Intensity
CentreName
$values = $_POST;
foreach ($values as &$value) {
$value = mysql_real_escape_string($value);
}
$sql1="INSERT INTO loan (loan_id)
VALUES ('$values[loan_id]')";
$result = mysql_query($sql1);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
When you create the table add the unique attribute to the fields you want to prevent, something like this
CREATE TABLE Persons
(
P_Id INT NOT NULL AUTO_INCREMENT,
LastName VARCHAR(255) NOT NULL,
FirstName VARCHAR(255),
Address VARCHAR(255),
City VARCHAR(255),
UNIQUE (P_Id)
)
If you already have created the table just edit it like this
ALTER TABLE Persons
ADD UNIQUE (P_Id)
Hope this helps you; If you do not have a unique id i believe this will suit you best on what you need; Note that this is not the full code; You need to add some to other information to fit in your question;
// Checks if the value already exist on the database
$query = SELECT EXISTS(SELECT column_name FROM table_name WHERE
condition LIMIT 1)
// If condition is not met it will proceed with save
if (mysql_num_rows(!$query) > 0) {
echo "Activity Booked";
} else { // If condition is met it will echo an error message
echo "Unable to booked activity"; }
You need to create a unique (composite) index on the column(s) that you wish to be unique. You can disregard your PK when making your unique index. In your case your sql would look something like:
Alter table yourtablename
add unique index idx_unq(`LastName`, `FirstName`, `Email`, `ContactNumber` `ClassName`, `Week`, `Intensity`, `CentreName`);
Then do an INSERT IGNORE INTO instead of an INSERT INTO.
This post may also help you.
"INSERT INTO .. ON DUPLICATE KEY UPDATE" Only inserts new entries rather than replace?
In order to see if record already exist in table you must first "test" to see if that exact record exist in your table. This is to be done before the 'Insert IGNORE Into' in your logic. Using the variables your code would look something like this:
$testcount = "Select count(`LastName`, `FirstName`, `Email`, `ContactNumber` `ClassName`, `Week`, `Intensity`, `CentreName`)
from yourtablename
where
(LastName = '$LastName' AND FirstName= '$FirstName' AND Email= '$EMAIL' AND ContactNumber= '$ContactNumber' AND ClassName= '$ClassName' AND Week= '$Week' Intensity = '$Intensity' AND CentreName = '$CentreName' )";
This query will give you back (assuming there are no duplicates already in the table) a 0 or a 1 and store it in your $testcount variable. This can then be used to either determine based on the value to insert the record into the table or print a message to end user informing them that it already exist.
I am not sure how you want to structure the php code but the psuedocode would look something like:
If $testcount = 1 then do your insert.
else if $testcount = 0 then echo your message.
I have the following table
id year name activation
1 2013 TEST 1
id A_I
year, name UNIQUE
name, activation UNIQUE
I use this query to INSERT/UPDATE data:
INSERT INTO LISTE_DATI
(year, name, activation)
VALUES
('$varray[1]', '$varray[2]', '$varray[3]')
ON DUPLICATE KEY UPDATE
year= '$yr',
name= '$na',
activation= '$act'
If I send this data to the table:
$yr = 2014
$na = TEST
$act = 0
the query INSERT data in the table. This is ok for me!
If I send this data to the table:
$yr = 2015
$na = TEST
$act = 1
the query UPDATES the first row (2013/TEST/1) in the table.
In this case I'd like to have an INSERT too.
How can I adjust it?
You are telling your INSERT query, that when it finds a duplicate (UNIQUE) key, to instead update that row.
You are inserting (2012, 'TEST', 1). This is a duplicate key; the name, activation key, your 2nd UNIQUE key! You already have a row with 'TEST', 1; the row with id=1.
The INSERT query updates that row, since it's a duplicate key.
You need to modify the keys on your table so that it reflects the data you want in it. What do you want the INSERT query to consider a duplicate? Create your UNIQUE keys based on that.
I'm trying to INSERT a new record into a table (employee) where a few of the columns are FK's that are linked to other tables (license and car) PK's. The table(1) has a default set for these columns that reflect the same value listed in the table(2+3) PK.
Example:
INSERT INTO employee (Emp_ID, Lic_ID, Car_ID) Values ('1234', ' ', ' ')
Tables:
table(1) = employee
PK = Emp_ID
FK = Lic_ID, default = 1
FK = Car_ID, default = 1
table(2) = license
PK = Lic_ID
records = 1 through 8
table(3) = car
PK = Car_ID
records = 1 through 6
The problem is, whenever I try to run that insert statement, I get:
Error: 1452 "Cannot add or update a child row: a foreign key constraint fails"
I don't want to have to enter a value into the Lic_ID or Car_ID fields when I create the employee because they may not have either one of those assigned to them. What I want is for the table to use the default value of '1', what am I doing wrong?
If you want to use default values, then remove field names from the INSERT statement -
INSERT INTO employee (Emp_ID) Values ('1234');