Same Auto Incremental ID Should be insert into Insert Query - php

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)

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 to add a variable value with auto increment value in an insert query

I have a localhost and I want to do something I hope I can explain it.
I have a table named 'students' in a database named 'theway', there is a column named 's_class_id' its kind is auto increment , and in php I insert some values in this table. But I want to insert a variable+the auto increment in the column named 's_class_id'.
For example : The variable's value is 'a', and the auto increment value is '5'. I want the value which be inserted in the 's_class_id' like this 'a5'.
Any help?
If it is auto-increment, the field should be an integer. Do not think that it is possible to change it to eg: 'a5'. You could run an update query searching for the s_class_id and update another string field to set it to be 'a5'.
You can do that task by folowing method,
First you need to insert record into theway table. After record insertion mysqli_insert_id($con) will return last inserted id. Then you need to update that row by using last inserted id.
// Insert Record
mysqli_query($con,"INSERT INTO theway (s_class_id) VALUES ('a')");
// Getting last inserted id
$lastInsertID = mysqli_insert_id($con);
$updatedValue = 'a'.$lastInsertID;
// Update same row with last inserted ida
$SameRowUpdate = "UPDATE theway SET s_class_id='".$updatedValue."' WHERE id=".$lastInsertID;
if (mysqli_query($conn, $SameRowUpdate )) {
echo "Record addedd successfully";
}

How to SELECT a record, UPDATE it and be sure it hasn't been updated in the mean?

I need to do something like that:
SELECT id FROM table WHERE option='1' ORDER BY time LIMIT 1
then with the id in $id
UPDATE table SET used='1' WHERE id='$id'
The problem is that this way another user can update the same record in the same time.
Is there a way to do that in one only operation ?
Thanks
UPDATE table SET used='1'
WHERE id=
(SELECT id FROM
(SELECT id FROM table
WHERE option='1'
ORDER BY time
LIMIT 1) AS tmptable
)
You need to use a three step query if you have concurrent access to the same row by different users.
First query has to reserve the row for a certain user (using a dedicated field).
Second query has to check if the row reservation is for that certain user.
Third query updates the row knowing there's no collision as that user reserved it.
Between step #1 and #2, multiple users can try to grab edit access to the row but in the end only one succeeds. The ones that failed will not reach step #3.
PS: This might be overkill for your needs but it's the best way to ensure multiple users work on tasks (rows) concurrently.
PPS: Or just combine the queries into a single one as another answer points out. But if your update requires some work done, it's best to decide upfront who will do the work before updating the value.
You could use: http://php.net/manual/en/mysqli.insert-id.php
mysql_insert_id
Finds the last id updated or set and stores it. We then check to make sure the last id does not exist.
so...
//last id being the id of the last query set or updated
$last_id = $mysql->insert_id;
if($last_id != $id) {
//execute code
{
else {
echo "last id already in database!";
}
If I misinterpreted the question you should still be able to see how to use that last id to do what you want.
Here is an example of it being used. First we update the table with the form data which created our ID. Then we add the input check boxes array to the last id updated.
//define input variables
$lesson_id = $_POST['lesson_id'];
$user_id = $_POST['user_id'];
$instructor_id = $_POST['instructor_id'];
$lesson_comments = $_POST['lesson_comments'];
$lesson_date = date("Y-m-d");
$video_ids = isset($_POST['checkbox']) ? $_POST['checkbox'] : array(); # this is called a ternary operator
//insert lesson information first
$query ="INSERT INTO swing_viewer_lessons (lesson_id, user_id, instructor_id, lesson_comments, lesson_date) VALUES (?, ?, ?, ?, ?)";
if ($stmt = $mysqli->prepare($query)) {
$stmt->bind_param("iiiss", $lesson_id, $user_id, $instructor_id, $lesson_comments, $lesson_date);
$stmt->execute();
//printf($stmt->error);
echo "successful";
//echo "$last_id";
}
//insert lesson information
if (is_array($video_ids) && count($video_ids) > 0)
{
foreach($video_ids as $list);
}
// Make it into a comma separated list
$rec_ids = implode(',', $video_ids);
//get last inserted id from above
$last_id= $mysqli->insert_id;
//finally query and update lesson information based on the last id added from above
$query ="UPDATE swing_viewer_lessons SET video_ids=? WHERE id=?";
if ($stmt = $mysqli->prepare($query)) {
$stmt->bind_param("si", $rec_ids, $last_id);
$stmt->execute();
}
Hopefully this helps you or anyone else for that matter, as at one point I was pulling hair at this.

How to check to see if a key exists before trying to insert it into a database?

I'm pulling data from a calendar feed and each event in the calendar has a unique $EventID string. I'm using PHP.
I have a SQL database with an Event_ID column. These IDs are strings. I need to be able to compare my $EventID against the Event_ID column and put in in the database if it's not there.
I have a primary key set up to auto increment in the database, and I was thinking I can set up a loop to increment through those and compare each to the $EventID, but I'm wondering if there is a better way-maybe a PHP function I don't know about?
I've got a whole lot of code, but basically I've got:
<?php
$EventID = $event->id; //This is the event ID
mysql_query("INSERT INTO myTable
(Event_ID, Date_added, Date_edited)
VALUES
('$EventID', '$dateAdded', '$lastEdited')");
?>
So how do I set up a conditional to check all the Event_IDs that are already in the database against the $EventID?
$query = "SELECT * FROM `myTable` WHERE `Event_ID`='$EventID' ";
$result = mysql_query($query);
if (!mysql_num_rows($result))
// INSERT QUERY
Check if the Event ID is present, If not insert it
You could just skip the "Select" query and do an "INSERT IGNORE" instead:
mysql_query("INSERT IGNORE INTO myTable
(Event_ID, Date_added, Date_edited)
VALUES
('$EventID', '$dateAdded', '$lastEdited')");
this will leave existing Event_id's, and just add new records if required.

How do I get all the ids of the row created by one multiple row insert statement

I'm new to php. So, please forgive me if this seems like a dumb question.
Say i have a MySQL insert statement insert into table (a,b) values (1,2),(3,4),(5,6). table 'table' has a auto increment field called 'id'.
how can I retrieve all the ids created by the insert statement above?
It will be great if i get an example that uses mysqli.
You can't. I would suggest that you maintain your own ids (using guid or your own auto-increment table) and use it when you insert into the table.
But it's possible to get the auto-increment value for the last inserted using LAST_INSERT_ID():
http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html
AngeDeLaMort's answer is almost right. Certainly, the most appropriate way to deal with the problem is to insert one row at a time and poll the insert_id or generate the sequence elsewhere (which has additional benefits in terms of scalability).
I'd advise strongly against trying to determine the last insert_id and comparing this the most recent insert_id after the insert - there's just too may ways this will fail.
But...an alternative approach would be:
....
"INSERT INTO destn (id, data, other, trans_ref)
SELECT id, data, other, connection_id() FROM source";
....
"SELECT id FROM destn WHERE trans_ref=connection_id()";
....
"UPDATE destn SET trans_ref=NULL where trans_ref=connection_id()";
The second query will return the ids generated (note that this assumes that you use the same connection for all 3 queries). The third query is necessary because connection ids to go back into the pool when you disconnect (i.e. are reused).
C.
In some cases, if you have another identifier of sort such as a UserID, you could filter your query by UniqueID's greater than or equal to mysql_insert_id(), limit by the number of affected rows and only display those by the user. This would really only work inside of a transaction.
$SQL = "INSERT INTO Table
(UserID, Data)
VALUES
(1,'Foo'),
(1,'Bar'),
(1,'FooBar')";
$Result = mysql_query($SQL);
$LastID = mysql_insert_id();
$RowsAffected = mysql_affected_rows();
$IDSQL = "SELECT RecordID
FROM Table
WHERE UserID = 1
AND RecordID >= '$LastID'
LIMIT '$RowsAffected'";
$IDResult = mysql_query($IDSQL);
as a follow up to AngeDeLaMort:
You could seperate your inserts and do it something like this:
$data = array (
array(1,2),
array(3,4),
array(5,6)
);
$ids = array();
foreach ($data as $item) {
$sql = 'insert into table (a,b) values ('.$item[0].','.$item[1].')';
mysql_query ($sql);
$id[] = mysql_insert_id();
}
Now all your new id's are in the $id array.
Maybe I can do this
$insert = "insert into table (a,b) values (1,2),(3,4),(5,6)";
$mysqli->query($insert);
$rows_to_be_inserted=3;
$inserted_id = $mysqli->insert_id // gives me the id of the first row in my list
$last_row_id = ($inserted_id+$rows_to_be_inserted)-1;
$mysql->query("select * from table where id between $inserted_id and $last_row_id");
what to you guys say?

Categories