How to create a Manual Insert ID while adding a new row? - php

I am trying to add new rows in my mysql table using PDO object, but it is giving me automated insert ID.
I need to make primary key values like -
key_1, key_2, key_3... etc.
But for now it's giving me the primary key value as 1,2,3..
Please suggest me some help , thank you.

Related

How to make MySQL display duplicate data into my table?

I know this has something to do with maybe the Primary Key and Unique Keys, but I'm not sure how to how to make it work. Basically I want MySQL to generate a new row even if data in it is duplicate of last rows. Right now, any duplicate data from previous rows result in the row not being generated. Help is very appreciated.
The table you have defined has all columns as primary key and unique. It's ideal to maintain one column as primary key (perhaps with auto increment) and the rest as non-indexed columns. Check the table definition with the following mysql query if you are not familiar with using phpMyAdmin
desc tablename;

#1062 - Duplicate entry '81057' for key 'PRIMARY'

I am not fluent in using phpmyadmin so please be gentle.
I have transferred wordpress sites in the past but they have small databases. Ive now moved a new clients site to my hosting and it is running with this error:
INSERT INTO `wp_options` VALUES ( 81057,
'_wc_session_6f1ee0a5a9d89e47f7941c9e3b3e1fed',
'a:20:{s:4:"cart";s:309:"a:1:{s:32:"7b1ce3d73b70f1a7246e7b76a35fb552";a:9:{s:10:"product_id";i:2103;s:12:"variation_id";s:0:"";s:9:"variation";s:0:"";s:8:"quantity";i:1;s:10:"line_total";d:23;s:8:"line_tax";i:0;s:13:"line_subtotal";d:23;s:17:"line_subtotal_tax";i:0;s:13:"line_tax_data";a:2:{s:5:"total";a:0:{}s:8:"subtotal";a:0:{}}}}";s:15:"applied_coupons";s:6:"a:0:{}";s:23:"coupon_discount_amounts";s:6:"a:0:{}";s:19:"cart_contents_total";d:23;s:20:"cart_contents_weight";i:0;s:19:"cart_contents_count";i:1;s:17:"cart_contents_tax";i:0;s:5:"total";i:0;s:8:"subtotal";d:23;s:15:"subtotal_ex_tax";d:23;s:9:"tax_total";i:0;s:5:"taxes";s:6:"a:0:{}";s:14:"shipping_taxes";s:6:"a:0:{}";s:13:"discount_cart";i:0;s:14:"discount_total";i:0;s:14:"shipping_total";i:0;s:18:"shipping_tax_total";i:0;s:9:"fee_total";i:0;s:4:"fees";s:6:"a:0:{}";s:10:"wc_notices";N;}',
no' ) ;`
#1062 - Duplicate entry '81057' for key 'PRIMARY'
I genuinely do not have a clue what this means and how to change it. I get that there is a duplicate entry and its to do with the primary key - which is set on option_id.
What i don't get is why it doesn't just add the entries into the database and auto increment them - which it is set to do? Also how can i resolve the issue and add the database?
please help !
AUTO_INCREMENT is a default value. If you specify a value for the field it will be used instead.
You can omit the value in the insert statement or use NULL instead.
It looks like the table in your source database has some inconsistency since you are only trying to copy all records to your new database.
Check if there are multiple records with same option_id in your source table and if there are some try to resolve them and then try the import again.
As i understand you are trying to do the manual transfer of the whole database and in that case AUTO_INCREMENT just wont work since you will break the relations between your model entities.
The way I see it, you have two options.
Omit the primary key value and allow mysql to create a new row and auto increment it. Of course this will require you to specify the columns.
INSERT INTO `wp_options`(column2, column3, etc)
VALUES('_wc_session_6f1ee0a5a9d89e47f7941c9e3b3e1fed', ...);
Notice that I left out the primary key
If the data needs to be added to that specific row, do an UPDATE instead.
UPDATE wp_options SET column2='_wc_session_6f1ee0a5a9d89e47f7941c9e3b3e1fed',
column3='something else', ...
WHERE column1=81057

Auto-incrementing field that isn't a primary key

In my MySQl table I have two fields, id and order. id is an auto-incrementing primary key and I want order's initial value to match this, but to also be editable, not a key and with no uniqueness constraints. How can my database insert method achieve this? Is it possible to do so without requerying to find the last inserted id?
I'm using paris/idiorm so a solution making use of their features would be handy, although plain SQL and php is fine too.
In MySQL (since version 5.0.2) you can create trigger.
Try this on non-production database:
create trigger default_order_value AFTER INSERT ON orders
UPDATE order SET order = id WHERE id = new.id;
It may not work in that way as you wish, but you can edit it. This is another trigger example:
CREATE TRIGGER default_order
BEFORE UPDATE ON orders
REFERENCING NEW ROW AS n
n.order = n.id;

How do I know when a field/row in mysql updated successfully?

Right now, I have my database setup so that I insert a new row. But if the row I'm trying to insert is a duplicate (based off of my primary key id), then I increment the count field by 1.
Right now I want to know when I was able to create a new row instead of having it increment count. How would I do this in an efficient/proper manner?
The current method I'm thinking of doing this, is by querying the id first and checking if it exists. But I feel like there's a faster/better way. I've also read about triggers but I've heard that they're bad/risky to use.
Use INSERT ... ON DUPLICATE KEY UPDATE...
Then query for affected_rows (as #Tarek Fadel suggested). MySQL will return 1 if the row was inserted, or 2 if existing row were updated.
Use your database AUTO INCREMENT option for your primary ID field. Only propper solution.
Here you have mysql reference, but that exist in just every database engine:
http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html
How about an auto_increment on the id column?
Otherwise you might use SELECT MAX(id) FROM TABLE to retreive the highest id and add one to it, but that isn't thread-safe since another user might execute the same insert at the same time. Auto_increment fixes that for you.
PHP's mysql_affected_rows()

Is it possible to insert a row but only if a value does not already exist?

Is it possible to insert a row, but only if one of the values already in the table does not exist?
I'm creating a Tell A Friend with referral points for an ecommerce system, where I need to insert the friend's email into the database table, but only if it doesn't already exist in the table. This is because I don't want any more than 1 person getting the referral points once the new customer signs up and purchases something. Therefore I want only one email ever once in the table.
I'm using PHP 4 and MySql 4.1.
This works if you have a unique index or primary key on the column (EmailAddr in this example):
INSERT IGNORE INTO Table (EmailAddr) VALUES ('test#test.com')
Using this if a record with that email already exists (duplicate key violation) instead of an error, the statement just fails and nothing is inserted.
See the MySql docs for more information.
If the column is a primary key or a unique index:
INSERT INTO table (email) VALUES (email_address) ON DUPLICATE KEY UPDATE
email=email_address
Knowing my luck there's a better way of doing it though. AFAIK there's no equivalent of "ON DUPLICATE KEY DO NOTHING" in MySQL. I'm not sure about the email=email_Address bit, you could play about and see if it works without you having to specify an action. As someone states above though, if it has unique constraints on it nothing will happen anyway. And if you want all email addresses in a table to be unique there's no reason to specify it as unique in your column definition.
Most likely something like:
IF NOT EXISTS(SELECT * FROM myTable WHERE Email=#Email) THEN INSERT INTO blah blah
That can be rolled into one database query.
A slight modification/addition to naeblis's answer:
INSERT INTO table (email) VALUES (email_address)
ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id)
This way you don't have to throw email=email_address in there and you get the correct value for LAST_INSERT_ID() if the statement updates.
Source: MySQL Docs: 12.2.5.3
MySQL offers REPLACE INTO http://dev.mysql.com/doc/refman/5.0/en/replace.html:
REPLACE works exactly like INSERT,
except that if an old row in the table
has the same value as a new row for a
PRIMARY KEY or a UNIQUE index, the
old row is deleted before the new row
is inserted.
I'm not sure if I got it, but what about a
try {
mysql_query($sql);
}
catch(Exception $e) {
}
combined with an unique field index in MySQL?
if it throws an exception then you know that you got a duplicated field.
Sorry if that don't answer your question..
If the email field was the primary key then the constraints on the table would stop a duplicate from being entered.

Categories