How to stop duplicate entries into database - php

Hi there i am trying to insert an array of information into fields in a database through the selection of checkboxes i have that sorted and inserting fine but i am able to insert duplicates which is no good i am using the following to insert the items
$list = $_POST['sub'];
// for each loop to insert each value into the database with the selected users informtion
foreach ($list as $value) {
// The query to run
$listQuery='INSERT INTO tbl_list (`userId`, `subId`) VALUES (\'' . $id . '\', \'' . $value . '\')';
// Run the query
$objects->query($listQuery);
}

You should add a unique key for (userId, subId):
ALTER TABLE tbl_list ADD UNIQUE(`userId`, `subId`)
Then, you should use either INSERT IGNORE or REPLACE INTO to avoid errors during insert.

You can use Insert Ignore instead of Insert in mysql query

For stop duplicate entries into database you have do this thing.follow step by step
> 1.set a unique key on the table
after Complete create unique key you have to decide what you want to do when there's a duplicate
> 2. ignore it
> 3.Overwrite the previously entered record
> Update some counter

You need to do two things
first make your userId primary key and then try this query
$listQuery='INSERT INTO tbl_list (userId, subId) VALUES (\'' . $id . '\', \'' . $value . '\') on duplicate key update userId = LAST_INSERT_ID()';

Related

Maria DB SQL Insert INTO ON DUPLICATE working only for first updated value

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.

How can I check with SQL if variable is exist in table

I'm creating function (PHP) which has to run every few hours and update some DB table.
1. If row isn't exist - INSERT new row
2. If row exist - UPDATE the current row
I want to write it the easiest and simplest way cause I'll do it for several tables.
You use the insert . . . on duplicate key update statement:
insert into dbtable(cols, . . . )
select <values here >
on duplicate key update col2 = values(col2), col3 = values(col3);
It is documented here.
EDIT:
Assuming you have some unique key on animals, your query would look something like:
insert into animals(animal_id, animal_name)
select #animal_id, #animal_name
on duplicate key update animal_name = values(animal_name);

PHP/MySQL insert string into database

I'm trying to insert multiple different words into a database if they are not already in the database. I'm getting the text from a textfield where the user inputs multiple categories. I want to split the text being passed from this textfield by comma and insert it individually into the database if it's not already in it. Currently nothing is being input into the database. Thanks in advance for your help!
Here is my code to split the textfield data and insert into the database:
$category = trim($_POST['category']);
$cat2 = explode(',', $category);
foreach ($cat2 as $new_interest)
{
$insert_user_interests = sprintf("INSERT INTO interests IF NOT EXISTS name = '". $new_interest . "'" .
"(name) " .
"VALUES ('%s');",
mysql_real_escape_string($new_interest));
mysql_query($insert_user_interests);
}
This is your insert statement:
INSERT INTO interests IF NOT EXISTS name = '". $new_interest . "'" .
"(name) " .
"VALUES ('%s')
As far as I'm aware, this is not valid insert syntax. (The documentation is here.) I think you are confusing it with the create table syntax. Instead, use ignore and something like:
INSERT IGNORE INTO interests(name) VALUES(". $new_interest . "')"
EDIT:
Right, if you don't want to insert duplicates, then create a unique index on name:
create index unique interests_name on interests(name);
Then the above query will do what you want.

Trigger to delete table and then insert value with Mysql

How could i do a query with php and mysqli, to remove an entire table and then add new I have a form where data is received, but before adding the new data, I want to remove all data from table.
$oConni is my connection string
$cSQLt = "TRUNCATE TABLE approved";
$cSQLi = "INSERT INTO approved (ID_STUDENT, YEAR, APPROVED)
VALUES (
'" . $_POST['NSTUDENT'] . "',
'" . $_POST['YEAR'] . "',
'YES'
)";
$oConni->query($cSQLt);
$oConni->query($cSQLi);
You can remove everything from a table with MySQL by issuing a TRUNCATE statement:
TRUNCATE TABLE approved;
.. which usually is the same as
DELETE FROM approved;
.. but there are a few small differences, which you can read about in the documentation.
In the code you've pasted, please use prepared statements to avoid a sql injection attack. Never use unfiltered POST-data directly in a query!
If you want to do this as a trigger, we'll need to know a bit more about your data handling. Issuing a TRUNCATE before a INSERT will usually lead to only one row being available in the table, which seems like a weird use case for actually using a table.
You could use TRUNCATE TABLE and then your next query:
$cSQLt = "TRUNCATE TABLE CALIFICA_APTO";
$cSQLi = "INSERT INTO approved (ID_STUDENT, YEAR, APPROVED)
VALUES (
'" . $_POST['NSTUDENT'] . "',
'" . $_POST['YEAR'] . "',
'YES'
)";
$Connect->query($cSQLt);
$Connect->query($cSQLi);
If your looking to remove all of the data from a table you should use TRUNCATE:
TRUNCATE TABLE approved
Then you can do your SQL statement.
NOTE: This will delete all data from the table, so be careful! Also, your database user must have the ability to truncate tables.

sql insert and update question

I have a form which to insert data into a database. This form takes the content of the fields, and then displays the result page showing the entered information in context. There is a link on this page to edit the user info, which go back to the previous form. Obviously, I do not want duplicate records inserted. Is there an easy way to use an update statement if a record already exists? I am doing this with ajax and php.
Take a look at:
INSERT ... ON DUPLICATE: http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
REPLACE INTO: http://dev.mysql.com/doc/refman/5.0/en/replace.html
INSERT ... ON DUPLICATE will allow you to issue an UPDATE query when a UNIQUE INDEX or PRIMARY KEY is matched.
REPLACE works exactly the same, but if the row is found, the old row is deleted prior to inserting a new one. When using cascading deletes, this is especially something to take into account!
MySQL supports the addition of ON DUPLICATE KEY UPDATE to an INSERT statement, which should do what you want.
Assuming you have a field like 'username' or 'email', you could make use of that field to check if a record already exists, if it does, update it.
$res = mysql_query("SELECT primary_key FROM my_table WHERE `email` = '" . mysql_real_escape_string($email) . "'");
if($row = mysql_fetch_array($res))
{
// Record exists, update it
$q = "UPDATE my_table SET `username` = '" . mysql_real_escap_string($username) . "' WHERE primary_key = " . (int) $row['primary_key'];
}
else
{
// Record doesn't exist, insert
$q = "INSERT INTO my_table(username, email) VALUES('" . mysql_real_escape_string($username) . "', '" . mysql_real_escape_string($email) . "');";
}
In the above example I assume you have a primary key field that's an integer (primary_key).
You should consider using an ORM like http://www.ezpdo.net/blog/?p=2
Plain SQL in web applications should only be used if absolutely neccessary, alone for security reason, but also to avoid problems like yours.

Categories