prevent duplicate records in mysql table - php

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.

Related

Insert values from 1 form into 2 sql server tables (PHP) (SQL-Server)

I want to use one form to insert into two different Microsoft sql tables. I tryed to use 2 inserts, but didnt work.
if (isset($_GET['submit'])) {
$sth = $connection->prepare("INSERT INTO DB.dbo.Fehler (QualiID, TestaufstellungID, ModulinfoID, failAfter, Datum, Verbleib, DUTNr) VALUES ($QualiID, $TestaufstellungID,$ModulinfoID,'$failAfter','$Datum','$Verbleib','$DUTNr')");
echo "INSERT INTO DB.dbo.Fehler (QualiID, TestaufstellungID, ModulinfoID, failAfter, Datum, Verbleib, DUTNr) VALUES ($QualiID, $TestaufstellungID,$ModulinfoID,'$failAfter',$Datum,'$Verbleib','$DUTNr')";
$sth->execute();
if($sth)
{
echo "";
}
else
{
echo sqlsrv_errors();
}
$MID = $connection->prepare("MAX(MID) as MID FROM DB.dbo.Fehler WHERE DB.dbo.Fehler.TestaufstellungID = '". $TestaufstellungID . "'");
$MID->execute();
$sth2 = $connection->prepare("INSERT INTO DB.dbo.Fehlerinfo (MID, Tester, Test, Ausfallbedingungen, Fehlerbeschreibung, Ersteller) VALUES ($MID, '$Tester','$Test','$Ausfallbedingungen','$Fehlerbeschreibung','$Ersteller')");
$sth2->execute();
To understand MID is the Primary key of table Fehler and ist the foreign key in the second table Fehlerinfo
Thats why i have the select work around to get the last MID and want to save it in a variable $MID to insert it into the second table.
Is there a smarter solution possible?
As I mentioned in the comments, generally the better way is to do the insert in one batch. This is very over simplified, however, should put you in the right direction. Normally you would likely be passing the values for the Foreign Table in a Table Value Parameter (due to the Many to One relationship) and would encapsulate the entire thing in a TRY...CATCH and possibly a stored procedure.
I can't write this in PHP, as my knowledge of it is rudimentary, but this should get you on the right path to understanding:
USE Sandbox;
--Couple of sample tables
CREATE TABLE dbo.PrimaryTable (SomeID int IDENTITY(1,1),
SomeString varchar(10),
CONSTRAINT PK_PTID PRIMARY KEY NONCLUSTERED (SomeID));
CREATE TABLE dbo.ForeignTable (AnotherID int IDENTITY(1,1),
ForeignID int,
AnotherString varchar(10),
CONSTRAINT PK_FTID PRIMARY KEY NONCLUSTERED(AnotherID),
CONSTRAINT FK_FTPT FOREIGN KEY (ForeignID)
REFERENCES dbo.PrimaryTable(SomeID));
GO
--single batch example
--Declare input parameters and give some values
--These would be the values coming from your application
DECLARE #SomeString varchar(10) = 'abc',
#AnotherString varchar(10) = 'def';
--Create a temp table or variable for the output of the ID
DECLARE #ID table (ID int);
--Insert the data and get the ID at the same time:
INSERT INTO dbo.PrimaryTable (SomeString)
OUTPUT inserted.SomeID
INTO #ID
SELECT #SomeString;
--#ID now has the inserted ID(s)
--Use it to insert into the other table
INSERT INTO dbo.ForeignTable (ForeignID,AnotherString)
SELECT ID,
#AnotherString
FROM #ID;
GO
--Check the data:
SELECT *
FROM dbo.PrimaryTable PT
JOIN dbo.ForeignTable FT ON PT.SomeID = FT.ForeignID;
GO
--Clean up
DROP TABLE dbo.ForeignTable;
DROP TABLE dbo.PrimaryTable;
As i mentioned the answer how it works for me fine atm.
if (isset($_GET['submit'])) {
$failInsert = ("INSERT INTO DB.dbo.Fehler (QualiID, TestaufstellungID, ModulinfoID, failAfter, Datum, Verbleib, DUTNr) VALUES ($QualiID, $TestaufstellungID,$ModulinfoID,'$failAfter','$Datum','$Verbleib','$DUTNr')");
$failInsert .= ("INSERT INTO DB.dbo.Fehlerinfo (MID, Tester, Test, Ausfallbedingungen, Fehlerbeschreibung, Ersteller) VALUES (NULL, '$Tester','$Test','$Ausfallbedingungen','$Fehlerbeschreibung','$Ersteller')");
$failInsert .= ("UPDATE DB.dbo.Fehlerinfo SET DB.dbo.Fehlerinfo.MID = i.MID FROM (SELECT MAX(MID)as MID FROM DB.dbo.Fehler) i WHERE DB.dbo.Fehlerinfo.TestID = ( SELECT MAX(TestID) as TestID FROM DB.dbo.Fehlerinfo)");
$sth = $connection->prepare($failInsert);
$sth->execute();
}

how to remove data duplicacy in customer table

i have a table customer_stock_entries.. i want to insert the item if the item and supplier is not available and i want to update the item if item and supplier is available
Example in my table i have stock_supplier_name and quantity. What i want to do is that if the stock supplier name entry is new then insert it into the table and if the entry is already there then delete the previous value in column 'quantity' and insert the new value.
i am stuck with this. Please help me out
I have tried something like this.
for ($i = 0; $i < count($stock_name); $i++) {
$count = $db->countOf("customer_stock", "name='$stock_name[$i]'");
if ($count == 0) {
$db->query("insert into customer_stock(name,quantity) values('$stock_name[$i]',$quty[$i])");
echo "<br><font color=green size=+1 >New Stock Entry Inserted !</font>";
$db->query("insert into stock_details(stock_id,stock_name,stock_quatity,supplier_id,company_price,selling_price) values('$autoid','$stock_name[$i]',0,'$supplier','$cost[$i]','$sell[$i]')");
$db->query("INSERT INTO customer_stock_entries(stock_id,stock_name, stock_supplier_name, quantity, company_price, selling_price, opening_stock, closing_stock, date, username, type, total, payment, balance, mode, description, due, subtotal,count1,billnumber) VALUES ( '$autoid1','$stock_name[$i]','$supplier','$quty[$i]','$cost[$i]','$sell[$i]',0,'$quty[$i]','$date','$username','entry','$total[$i]','$payment','$balance','$mode','$description','$due','$subtotal',$i+1,'$bill_no')");
} else if ($count == 1) {
$amount = $db->queryUniqueValue("SELECT quantity FROM customer_stock WHERE name='$stock_name[$i]'");
$amount1 = $amount + $quty[$i];
$db->execute("UPDATE customer_stock SET quantity='$amount' WHERE name='$stock_name[$i]'");
$db->query("INSERT INTO customer_stock_entries(stock_id,stock_name,stock_supplier_name,quantity,company_price,selling_price,opening_stock,closing_stock,date,username,type,total,payment,balance,mode,description,due,subtotal,count1,billnumber) VALUES ('$autoid1','$stock_name[$i]','$supplier','$quty[$i]','$cost[$i]','$sell[$i]','$amount','$amount1','$date','$username','entry','$total[$i]','$payment','$balance','$mode','$description','$due','$subtotal',$i+1,'$bill_no')");
Thanks
Typical solution to this problem involve following typical steps:
Check if the record for the stock supplier exists by using a select query and if it exists, update the quantity attribute.
If the the record doesn't exist, then insert the record in the table.
Sample Code as requested:
IF EXISTS(SELECT * FROM Users WHERE UserId = #UserId)
BEGIN
UPDATE TC_Users SET Salary = 25000 WHERE UserId = #UserId
END
ELSE
BEGIN
INSERT INTO TC_Users(UserId, Salary) VALUES(#UserId, 25000)
END
Hope this helps you.
Hare are some information's regarding your problem:
Primary Keys (To Avoid Duplication Of Data) :
Always use primary keys in your Database Table Structure i.e consider one column as primary key in order for it to be unique so that duplicate value won't be able to be inserted in your records.
Example : For instance I have a table with following columns as id,username,password,name .Now in order for to avoid duplication of data i.e that I don't want people to register with same username which means that username column value should be unique so instead I mark my username column as Primary Key.So now the new upcoming members won't be able to register with the same username which is already available in database i.e someone already registered using that username.Instead they will be needed to register with unique username.
Solution :
While here is code for to update your quantity value if supplier is already present in the database and if not so then insert the new record..!
$supplier_name = $_POST['supplier];
$query = mysqli_query($mysqli,"SELECT * FROM table");
$results = mysqli_fetch_array($query);
for ($i=0;$i<=count($results);$i++) {
//IF supplier is available in database
if ($results[$i]['supplier'] == $supplier_name) {
$query = mysqli_query($mysqli,"UPDATE table SET quantity=$quanity_new_value WHERE supplier=$supplier_name");
} else {
// If supplier is not available in database so it will insert new record
$query = mysqli_query($mysqli,"INSERT INTO table (supplier, quanity, email) VALUES ($supplier_name, $quantity, $email)");
}
}

how to prevent insert duplication data in MySQL

i have this code that work well.
$sql = "INSERT IGNORE INTO phpc_events (cid, owner, subject, description, ctime)
SELECT '1', '1', title, description, start_tdate from at_courses";
mysql_query($sql);
i put this into this page :
> http://localhost/msigilearnv2/tools/calender/copy_database.php
when first runs the page it will copy table from at_courses to phpc_events..
when second runs.. how i can prevent duplication data? because it keep add same data. i put ignore but still not works
I am sharing you one of the alternative. Lets say you have a record in the database and cid value is '1'.
First step check the value if it is already exists in the database.
$sql = "SELECT cid FROM phpc_events";
$returned = mysql_query($sql);
if(mysql_num_rows($returned) > 0){
while( $row = mysql_fetch_array($returned) ){
$PhpcArray [] = $row; //stores result returned in array to ensure less resource used
}
}
$sqlC = "SELECT anotherId FROM at_courses";
$returnedC = mysql_query($sqlC);
if(mysql_num_rows($returnedC) > 0){
while( $rowC = mysql_fetch_array($returnedC) ){
if( in_array( $rowC['anotherId'], $PhpcArray ) ){
// do nothing as id is already exists in phpc_events
}
else{
// do insertion because id in at_courses is not exist yet in phpc_events
}
}
}
Hope this helps.
Another alternative.
By the way you can also try this query if it matches your column as I don't know how your table structure looks like
SELECT cid
FROM at_courses
WHERE cid NOT IN (
SELECT cid FROM phpc_events
)
This query will return the cid in the at_courses which is not yet occur in phpc_events. Then do the insertion for those cid returned from at_courses table.
Thank you.
My MySQL isn't great, but you will need to do something the like:
$sql = "INSERT IGNORE INTO phpc_events (cid, owner, subject, description, ctime)
SELECT '1', '1', title, description, start_tdate from at_courses"
left join phpc_event on phpc_events.cid = at_courses.cid //(and others you want matched for dups
where phpc_events.cid is null
;
If you have a primary key in your tables, you can replace INSERT with REPLACE. This will insert new records or replace them if the primary key already exists.
alter the table by adding UNIQUE constraint
ALTER TABLE phpc_events ADD CONSTRAINT your_field UNIQUE (cid, owner, subject, description, ctime)

Check whether records exist in database

I know there are various offered solutions for this topic posted on this site, and I checked (and used) some of those solutions. Nevertheless, I can't figure out why my code below does not work, probably because I'm a starter with respect to php and sql programming ;-(
The code is supposed to add a record with 3 fields (FirstName, LastName, Age) in a table (persons), but only if the record does not already exist. Therefore a check on existing FirstName and Lastname fields is performed. But in case of existing record the condition of the if statement still seems to be true and a copy of the existing record is still inserted into the database. What do I miss?
Thanks in advance for the help.
//check whether item does not exist in database
$query ="SELECT FirstName,LastName FROM persons
WHERE FirstName='$data[1]' AND LastName='$data[2]'";
$result = mysql_query($query);
if($result && mysql_num_rows($result) > 0)
{
echo " <br> record exist";
}
else
{
$theage = (int)$data[3]; //! for conversion of integer values
$sql="INSERT INTO persons (FirstName, LastName, Age)
VALUES ('$data[1]','$data[2]','$theage')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
}
You have to use {} around array values in query
$query ="SELECT FirstName,LastName FROM persons
WHERE FirstName='{$data[1]}' AND LastName='{$data[2]}'";
Also your INSERT query runs on mysqli and SELECT query runs on mysql. You have to use only 1 not both and use below code with mysqli.
$result = mysqli_query($con,$query);
if($result && mysqli_num_rows($result) > 0)
{
echo " <br> record exist";
}
May be this query will help you:
INSERT INTO persons (FirstName, LastName, Age)
SELECT * FROM (SELECT FirstName,LastName) AS tmp
WHERE NOT EXISTS (
SELECT FirstName, LastName FROM persons WHERE WHERE FirstName='$data[1]' AND LastName='$data[2]'
) LIMIT 1;
Check your connection
In first query you have used
mysql_query
then in second case at the time of insert you use
mysqli_query
From the database perspective, modify your Person table design by setting a UNIQUE KEY for the necessary fields i.e :
CREATE TABLE `Persons` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`FirstName` varchar(255) NOT NULL,
`LastName` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `unique_FirstName_LastName` (`FirstName`,`LastName`) USING BTREE
)ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;
Do a normal insert, handle the duplicate error
[Err] 1062 - Duplicate entry 'jk-kenneth' for key 'unique_FirstName_LastName'

php/mysql creating duplicate records with multiple tables

I'm building a database for making hotel reservations. One table called "reservations" holds the general details of the reservation, while another called "rooms" holds details about specific rooms (each reservation has many rooms, each room belongs to only one reservation).
I would like to be able to easily generate duplicate reservations records (except for the primary key, of course). My problem is in generating the rooms data as an array which is then inserted into the rooms table while being associated to its reservation.
I've come as far as the following trivial code (stripped down to the bare essentials for discussion purposes).
if (isset($_POST['action']) and $_POST['action'] == 'Duplicate')
{
include $_SERVER['DOCUMENT_ROOT'] . '/includes/connect.inc.php';
$id = mysqli_real_escape_string($link, $_POST['id']);
// retrieve reservation
$sql = "SELECT type_of_reservation FROM reservations WHERE id='$id'";
$result = mysqli_query($link, $sql);
$row = mysqli_fetch_array($result);
$type_of_reservation = $row['type_of_reservation'];
// create new reservation record
$sql = "INSERT INTO reservations SET type_of_reservation ='$type_of_reservation'";
$id = mysqli_insert_id($link);
// retrieve rooms
$sql = "SELECT reservation_id, in_date FROM rooms WHERE reservation_id='$id'";
$result = mysqli_query($link, $sql);
while ($row = mysqli_fetch_array($result))
{
$rooms[] = array('reservation_id' => $row['reservation_id'], 'in_date' => $row['in_date']);
}
The big question is, now what? Everything I've tried either generates an error or no new entries, and I can't seem to find any discussion that addresses this specific need. Thanks for your help.
PeterC, there is no code listed that shows you inserting the ROOM record information. In the //retrieve room section of your code, you are pulling the data and putting it into an array. If you really want to create a duplicate records, I would use in insert inside the database, then you don't have to pull the records out just to put them back in.
The bit of code you want will be something like this. It will be in place of the //retrieve rooms code you have listed: (psuedo code) [note: $id represents the newly selected id from your sql insert for the duplicated reservation]
INSERT INTO rooms(res_id, other, data)
SELECT $id, other, data FROM rooms WHERE id = $_POST['id'];
This will allow you to duplicate the room data, adding the new reservation_id right inside the database. No need to pull out the records, create inserts, and then put them back in. You can read more about INSERT INTO ... SELECT statements here: http://dev.mysql.com/doc/refman/5.0/en/ansi-diff-select-into-table.html
// create new reservation record
$sql = "INSERT INTO reservations SET type_of_reservation ='$type_of_reservation'";
//ADD HERE CODE BELOW
$id = mysqli_insert_id($link);
with mysql_insert_id you get the inseted id, but you should insert it into db.. so add
mysqli_query($link, $sql);
before retrieving data
If you simply need to duplicate records, you can do it this way:
INSERT INTO
reservations
(
SELECT
null, # assume first column is auto incrementing primary key, so leave null
`all`,
`other`,
`column`,
`names`
FROM
reservations
WHERE
reservation_id = $oldReservationId # id of reservation to duplicate
)
Then for the rooms use the last inserted id (for instance retrieved with mysql_insert_id), like this:
INSERT INTO
rooms
(
SELECT
null, # assume first column is auto incrementing primary key, so leave null
$newReservationId, # this is the new reservation id
`all`,
`other`,
`column`,
`names`
FROM
rooms
WHERE
reservation_id = $oldReservationId # id of reservation to duplicate
)

Categories