I have this query in PHP
$id = ibase_gen_id(TABLE1_ID_GEN);
$query = "UPDATE OR INSERT INTO TABLE1(ID, TESTER_ID, LOT_ID, TEST_STEP) VALUES (.....)
MATCHING (TESTER_ID, LOT_ID, TEST_STEP)";
$processQuery = ibase_query($query);
this query works but when updating the record, the ID also updated. I want to update the record (TESTER_ID, LOT_ID, and TEST_STEP) without updating/changing its ID.
Thanks!
Related
I am working a database where, I insert a row in a particular table. Then for some reason I update the same row from the same table and then fetch the values from that row in a html form. Now, the issue is when I do this, the first time I fetch the values it is correctly functioning. The next time I do this (normally after 12 to 24 hours) the values are not being fetched. I checked the database, the table no longer holds the record that I updated earlier. I am confused over this. Is there any solution for this. Please help. Thanks.
Here is my update query that I use to update the record :
$upd = "update billingrates set FirstCopyFront='".$firstcopy1."', FirstCopyFB='".$firstcopy2."', Upto50F='".$Lfiftycopies1."', Upto50FB='".$Lfiftycopies2."', Morethan50F='".$Mfiftycopies1."', Morethan50FB='".$Mfiftycopies2."', PrinterType='".$printertype."' where PaperTypeId = '".$id."' and CustomerId = '".$cid."'";
And this is how I am getting the values from previous form that I am using for updation :
$firstcopy1 = trim(mysqli_real_escape_string($link, $_POST['firstcopy'][0]));
$firstcopy2 = trim(mysqli_real_escape_string($link, $_POST['firstcopy'][1]));
$Lfiftycopies1 = trim(mysqli_real_escape_string($link, $_POST['Lfiftycopies'][0]));
$Lfiftycopies2 = trim(mysqli_real_escape_string($link, $_POST['Lfiftycopies'][1]));
$Mfiftycopies1 = trim(mysqli_real_escape_string($link, $_POST['Mfiftycopies'][0]));
$Mfiftycopies2 = trim(mysqli_real_escape_string($link, $_POST['Mfiftycopies'][1]));
Is there a better or faster way to return the ID?
The column customer is unique
$inserted_id = null;
if( !$mysqli->query("INSERT INTO users (id,customer) VALUES(null,'foo')" ){
// Is it possible to avoid this 2nd query?
$result = $mysqli->query("SELECT id FROM users WHERE customer='foo'");
$inserted_id = $result->fetch_assoc()['id'];
} else {
$inserted_id = $mysqli->insert_id;
}
Use $last_id = $mysqli->insert_id(); after your insert. That get's the last generated auto increment. Your code as it stands will not be accurate. Updated for Object Oriented perspective.
You can modify the insert query to UPDATE auto incremented column when a duplicate record is attempted to INSERT.
INSERT INTO users (id,customer)
VALUES (null,'foo')
ON DUPLICATE KEY UPDATE
id = LAST_INSERT_ID(id)
id = LAST_INSERT_ID(id) will return the value of the AUTOINCREMENT column for the last INSERT and set the value for mysqli_insert_id. This will make last insert id available during all inserts.
Have modified your code:
$inserted_id = null;
if($mysqli->query("INSERT INTO users (id,customer) VALUES(null,'foo') ON DUPLICATE KEY UPDATE id = LAST_INSERT_ID(id)" )
{
$inserted_id = $mysqli->insert_id; // Will return last insert ID in case of successful inserts as well as failed inserts due to duplicate key
}
I have the following two tables
Table player:
player_id (int)(primary)
player_name (varchar)
player_report_count (int)
Table report:
report_id (int)(primary)
player_id
report_description
report_location
Firstly I ask the user for the player_name and insert it into the player database. From here the player is given an id.
Then I tried to grab the value of the players report count and increment the current value by one (which isn't working).
This is followed by grabbing the playerId from the player table and then inserting into the corresponding column from the report table (also does not work).
When I insert some values into the database, the names, description and report are added to the database however the playerID remains at 0 for all entries and the player_report_count remains at a consistent 0.
What is the correct way to make these two features function? And also is there a more efficient way of doing this?
<?php
$records = array();
if(!empty($_POST)){
if(isset($_POST['player_name'],
$_POST['report_description'],
$_POST['report_location'])){
$player_name = trim($_POST['player_name']);
$report_description = trim($_POST['report_description']);
$report_location = trim($_POST['report_location']);
if(!empty($player_name) && !empty($report_description) && !empty($report_location)){
$insertPlayer = $db->prepare("
INSERT INTO player (player_name)
VALUES (?)
");
$insertPlayer->bind_param('s', $player_name);
$reportCount = $db->query("
UPDATE player
SET player_report_count = player_report_count + 1
WHERE
player_name = $player_name
");
$getPlayerId = $db->query("
SELECT player_id
FROM player
WHERE player_name = $player_name
");
$insertReport = $db->prepare("
INSERT INTO report (player_id, report_description, report_location)
VALUES (?, ?, ?)
");
$insertReport->bind_param('iss', $getPlayerId, $report_description, $report_location);
if($insertPlayer->execute()
&& $insertReport->execute()
){
header('Location: insert.php');
die();
}
}
}
Main issue here is you are getting player details before inserting it. $getPlayerId will return empty result always.
Please follow the order as follows.
Insert player details in to player table and get payerid with mysql_insert_id. After binding you need to execute to insert details to the table.
Then bind and execute insert report .
Then update the player table by incrementing report count with playerid which you got in step 1.
Note : use transactions when inserting multiple table. This will help you to rollback if any insert fails.
MySQL Query will return result object. Refer it from here https://stackoverflow.com/a/13791544/3045153
I hope it will help you
If you need to catch the ID of the last insterted player, This is the function you need if you're using PDO or if it's a custom Mysql Class, you need the return value of mysql_insert_id() (or mysqli_insert_id()) and then directly use it in the next INSERT INTO statement
I'm using $id = mysqli_insert_id($connection); to get the last inserted id, but in case if it updates any record in the table, it returns 0 as last inserted id.
Is there any way to handle this?
I want to get id each time weather it's inserting or updating.
Thanks
Edit
I need this id to be used for inserting data into table2
id from tab1
put data into tab2 where id from tab1 is FK
and most important, I'm not using the update with where clause
Here is my code that I'm using
$val = utf8_encode($val);
mysqli_set_charset($connection, 'utf8');
mysqli_query($connection, "SET NAMES 'utf8'");
mysqli_query($connection, "SET FOREIGN_KEY_CHECKS = 0;");
$sql = "INSERT INTO leaks($insert) VALUES($val)";
$sql .= " ON DUPLICATE KEY UPDATE `url` = '".mysqli_real_escape_string($connection,$data['url'])."';";
mysqli_query($connection, ($sql))or die(mysqli_error($connection)."<br />".print($sql));
$id = mysqli_insert_id($connection);
$proofs['leaks_id'] = $id;
mysqli_query($connection, "SET FOREIGN_KEY_CHECKS = 0;");
print_r($id);
$this->insertProofs($connection, $proofs);
connection::close_connection($connection);
Please note down that $this->insertProofs($connection, $proofs); inserts data to table2 on the base of key passed to it
On INSERT
After executing an INSERT query, using mysqli_insert_id() is absolutely fine.
On UPDATE
Depending on your update, you;
Would know the id's you're updating
Know the criteria to search for the id's from the update.
For example, if your UPDATE was something like;
UPDATE `foo` SET `x`='y' WHERE `a`='b'
You can then run
SELECT `id` FROM `foo` WHERE `a`='b'
to fetch the updated id's.
Edit
I see you're using ON DUPLICATE KEY UPDATE.
You can modify your query to become (assuming id is the primary auto_increment key)
ON DUPLICATE KEY UPDATE
`url` = '".mysqli_real_escape_string($connection,$data['url'])."',
id = LAST_INSERT_ID(id)
Then you can use mysqli_insert_id() regardless of if it was an UPDATE or INSERT
For example, if I run (with a record of id=2 exists; so we'll update);
INSERT INTO foobar (id, foo) VALUES (2, 'bar') ON DUPLICATE KEY UPDATE foo = 'baz', id = LAST_INSERT_ID(id);
SELECT LAST_INSERT_ID();
The output is 2, as that was the last insert id.
I'm trying to copy from one table to another table and it works fine, however I also need to insert the current user ID in the new table. I haven't yet figured out how. Normally I would do something like SET user_id = :user_id, but i have never worked with this one.
This is my code:
$q = $conn->prepare("INSERT INTO user_themes(title,code_entry,code_home,code_css,code_category,code_archive)
SELECT title, code_entry, code_home, code_css, code_category, code_archive FROM blogy_themes WHERE id = :id");
So my question is:
How can I insert user_id (let's say user_id is 1) into the new table as well?
The basis of your query doesn't change. Just add the value to both the columns and `SELECT statement:
INSERT INTO user_themes(user_id, title,code_entry,code_home,code_css,code_category,code_archive)
SELECT :user_id, title, code_entry, code_home, code_css, code_category, code_archive
FROM blogy_themes WHERE id = :id
Then when you execute, bind both :id and :user_id.
From what I understand you want to have the id of the user that is doing the action in all of the new records, you can do something like:
$q = $conn->prepare("INSERT INTO user_themes(user_id,title,code_entry,code_home,code_css,code_category,code_archive)
SELECT '" . (int) $userid ."' as user_id, title, code_entry, code_home, code_css, code_category, code_archive FROM blogy_themes WHERE id = :id");
This is a workaround in order to keep using the query as it is.
Second option is more "ORM" approach, you can query all the relevant records from the user_themes table, iterate on the result set, clone each row and save it with new user_id.