MySQL INSERT --- get the ID (auto_increment) IF one value is UNIQUE - php

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
}

Related

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

Last insert id issue--How to fetch it

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.

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

UPSERT using InnoDB engine?

Here is the solution for an UPSERT that uses primary key idfill to check for duplicates. I'm just not sure if it's sql injection proof or even efficient?
$idq="SELECT idafill FROM afillInfo, actorsInfo
WHERE (actorsInfo.id = afillInfo.id_actor) AND email = '$_SESSION[email]'" or die (mysql_error());
$sql = "INSERT INTO afillInfo (idfill, agency, agentPhone, afillChoice, id_actor)
VALUES ( ?,?,?,?, ( select id FROM actorsInfo WHERE email = ?))
ON DUPLICATE KEY UPDATE
`id_actor` = VALUES(`id_actor`),
`agency` = VALUES(`agency`),
`agentPhone` = VALUES(`agentPhone`),
`afillChoice` = VALUES(`afillChoice`)
";
if (($stmt = $con->prepare($sql)) === false) {
trigger_error($con->error, E_USER_ERROR);
}
$result= mysqli_query($con, $idq);
$row_number = 1;
while ($row = mysqli_fetch_array($result)) {
$idfill= $row["idafill"];
}
if ($stmt->bind_param("sssss",
$idfill,
$_POST["agency"], $_POST["agentPhone"],
$_POST["afillChoice"], $_SESSION["email"]) === false) {
trigger_error($stmt->error, E_USER_ERROR);
}
if (($stmt->execute()) === false) {
trigger_error($stmt->error, E_USER_ERROR);
}
INSERT adds a new row if it can.
When you use INSERT...ON DUPLICATE KEY UPDATE, it performs an UPDATE only if your INSERT would create a duplicate value in a primary key or unique key column.
Thank you for posting your table definition. I see now that you have no UNIQUE column besides idfill, the primary key.
So if you don't specify a value for idfill, it'll generate a new value in a new row. There's no way this will trigger the duplicate key. It makes no sense to run the query as you are doing and not expect it to create a new row.
You must specify an existing value in your INSERT statement for a PRIMARY or UNIQUE KEY, in order to cause the INSERT to fail and fall through to do the UPDATE. Otherwise the INSERT will succeed, by creating a new row with a distinct value for the primary key.
So you must add the idfill column to your INSERT, and specify a value that conflicts with one already existing in the database.
INSERT INTO afillInfo (idfill, agency, agentPhone, afillChoice, id_actor)
VALUES (?, ?, ?, ?, ( SELECT id FROM actorsInfo WHERE email = ?))
...
Apologies that I didn't notice this immediately, but another problem is that the UPDATE part of your statement isn't changing anything.
... UPDATE
`id_actor` = `id_actor`,
`agency` = `agency`,
`agentPhone` = `agentPhone`,
`afillChoice` = `afillChoice`
This sets the columns to exactly the same values they had before. It's a no-op. It's the equivalent of doing this in PHP:
$sql = $sql;
You can work around this by using the VALUES() function to re-use the values you tried to insert. Here's an example:
... UPDATE
`id_actor` = VALUES(`id_actor`),
`agency` = VALUES(`agency`),
`agentPhone` = VALUES(`agentPhone`),
`afillChoice` = VALUES(`afillChoice`)

PHP + SQL - insert value of primary key to another field in the same row

I need to insert a row to table where second element of the row (chatID) copies value of auto incremented primary key (messageID).
safe_query("INSERT INTO ".PREFIX."messenger ('messageID', 'chatID') VALUES('','')");
Any ideas would be very helpful. Thanks.
In php when you inserted the record get the lastInsertId(); and update the chatID
$inserted_id = $pdo->lastInsertId();
$sth2 = $pdo->prepare("UPDATE ".PREFIX."messenger
SET `chatID`= $inserted_id WHERE `messageID`=$inserted_id");
$sth2->execute();

Categories