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

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);

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.

INSERT ...ON DUPLICATE KEY UPDATE when key is not always known?

I'm trying to update a record if the key is known else I want to insert it and get the inserted id, currently I have:
if(isset($data['applicationId']))
{
//update
$sql="
UPDATE myTable SET data='jsonstring' WHERE id = {$data['applicationId']}
";
}
else
{
//insert and get id
$sql="
INSERT INTO myTable SET data='jsonstring'
";
}
Is it possible to simplify the above to one query using INSERT ...ON DUPLICATE KEY UPDATE even when the key is not always known ?
I've tried this:
INSERT INTO myTable
(
id,
data
)
VALUES
(
?, # <- I may not know this!!
'jsonstring'
)
ON DUPLICATE KEY UPDATE
data = 'jsonstring'
Thanks for any suggestions.
Yes, you can do that, assumed id is your primary key and auto_increment. You will have two different queries, one if you know the applicationId and one when you not knowing it.
The first, when you know it:
INSERT INTO myTable
(
id,
data
)
VALUES
(
1337, # <- insert id
'jsonstring'
)
ON DUPLICATE KEY UPDATE
data = 'jsonstring';
And the one if the applicationId is unknown:
INSERT INTO myTable
(
id,
data
)
VALUES
(
NULL, # <- This will cause mysql to use a auto_increment value
'jsonstring'
)
ON DUPLICATE KEY UPDATE
data = 'jsonstring';
So you can conclude this to:
$sql="INSERT INTO myTable
(
id,
data
)
VALUES
(" .
isset($data['applicationId']) ? $data['applicationId'] : 'NULL'
.",
'jsonstring'
)
ON DUPLICATE KEY UPDATE
data = 'jsonstring';
";
But be aware of How can I prevent SQL-injection in PHP?
Happy coding
Please forgive because your question is not 100% clear. However, the concept I can tell is that you want to be able to ask more than 1 query on 1 sql statement. That can be done with a multi-query command. However, if you want some of your data from a query placed in your next query I do not think it will work. Link provided for multi_query
http://php.net/manual/en/mysqli.quickstart.multiple-statement.php
First, Simple update query will run. If it runs successfully, it will not go to if condition and your ID will be the one which was used in updating.
And, if that ID is not available (means update query fails, $Query will be false), so pointer jumps to if condition and insert the query. Now, new Inserted ID we can get.
$ID=$data['applicationId'];
$Query=mysql_query("UPDATE myTable SET data='jsonstring' WHERE id='$ID' ");
if(!$Query)
{
$InsertQuery=mysql_query("INSERT INTO myTable SET data='jsonstring'");
$ID=mysql_insert_id();
}
So, $ID will be your ID.(either updated or currently inserted)

updating database row

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']'";

How to detect if a record has been modified in MySQL and php

I am coding an application using php/MySQL. I got to a scenario where I need to update a record if it exists but if it does not exist then insert a new record.
Please note that I can NOT add unique indexes so I can not use REPLACE or INSERT INTO... ON DUPLICATE KEY UPDATE. also I don't know the primary key for the record that I am trying to update.
this is my update statement
UPDATE surveys_answers_controller
SET controller_id = $field['answer']
WHERE group_id = $group_id AND question_id = $field['question_id']
note that neither group_id nor question_id are a primary key in this table but a foreign keys.
I tried to use $db->lastInsertId() but it is always returning 1 wether it update a record or not. I am not sure why!
this is what I tried
$update_answer = $db->processQuery('UPDATE surveys_answers_controller
SET controller_id = ?
WHERE group_id = ? AND question_id = ? ',
array($field['answer'], $group_id, $field['question_id']) );
$last_id = $db->lastInsertId();
if(empty($last_id)){
$update_answer = $db->processQuery('INSERT INTO surveys_answers_controller( controller_id, group_id, question_id)VALUES(?,?,?)',
array($field['answer'], $group_id, $field['question_id']) );
}
$last_id is always returning 1 for some reason whether it did modify a record or not and that is why the insert statement is ignored.
I am using PDO to connect to the database not mysqli.
How can I write a query that check for existing record and it update it if exists otherwise it inserts it?
Thanks
Use PDOStatement::rowCount() instead of $db->lastInsertId. This finds the number of rows affected by the last update/insert/delete. If zero then do the insert.

How to stop duplicate entries into database

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()';

Categories