I have a MySQL table that has Auto-increment on the ID field. However I need to create, via php, two rows with the same id.
I've tried using $last_id = intval(mysql_insert_id()); But just can't get to set the id on the second row. I am very new to php and SQL has never been my closest friend.
$sql = "INSERT INTO 'table name' (name, age, phone) VALUES ({$name}, {$age}, {$phone});"
$result = mysqli_query($conn, $sql);
Then I would like to run the same insert statement again, maybe with the phone being different, but with the ID being the same.
Your problem here is the auto_increment ID field. This is a primary key, since any auto_increment field must be defined as the table's primary key and therefore cannot have duplicate records.
What you could do is create and additional field for your "ID" field that you want to duplicate and then you can insert normally and leave the auto incrementing field do it's thing.
Related
I'm using the following code:
$db = new SQLite3('test.db');
$db->exec("CREATE TABLE IF NOT EXISTS items(id INTEGER PRIMARY KEY, the_id TEXT UNIQUE, type TEXT)");
$db->exec("INSERT INTO items(the_id) VALUES ('abc')");
$db->exec("UPDATE items SET type = 'One' WHERE the_id = 'abc'");
$final = $db->query("SELECT * FROM items");
print_r($final->fetchArray(SQLITE3_ASSOC));
However, I keep receiving a SQLite3::exec(): UNIQUE constraint failed: for $db->exec("INSERT INTO items(the_id) VALUES ('abc')");.
How can I insert new rows into the table?
If the table is empty, the script will run fine and add a new row.
If the table contains 1 record, it will run without errors but a new row won't be added, even when the_id is unique.
If the table contains 1 record and I run it again, it will run with the error mentioned above.
How can I add new rows into this table?
Edit
Just to confirm, I am adding different the_id values and it will only allow for a maximum of 1 in the table for some reason, when the values are unique
It seems you have a second field which must be unique: "id" that is also the primary key.
Either you force the value at every new insert (and must be unique) or you set it as an auto-increment in the table and it gets generated by the dB in an automatic sequence
I suggest the second one: add an AUTOINCREMENT keyword after the id field in table create statement
I have the following database MySQL table.
id (PK, AI)
email
country
lastlogin
I have a regular query in PHP that inserts this into the table.
however, logically, if this code runs several times, the same row will be inserted to the database every time.
I want my reference for checking and duplication to be the email field, and if the email is the same, update the country and the lastlogin.
I checked on other questions for a similar issue and the suggested way was to use ON DUPLICATE KEY like this
INSERT INTO <table> (field1, field2, field3, ...)
VALUES ('value1', 'value2','value3', ...)
ON DUPLICATE KEY UPDATE
field1='value1', field2='value2', field3='value3', ...
However, my primary key is not the email field rather the id but I don't want to run the check on it.
One option is make the email field unique, and then it should behave the same as primary key, at least with regard to MySQL's ON DUPLICATE KEY UPDATE:
ALTER TABLE yourTable ADD UNIQUE INDEX `idx_email` (`email`);
and then:
INSERT INTO yourTable (email, country, lastlogin)
VALUES ('tony9099#stackoverflow.com', 'value2', 'value3')
ON DUPLICATE KEY UPDATE
email='value1', country='value2', lastlogin='value3'
If the email tony9099#stackoverflow.com already exists in your table, then the update would kick in with alternative values.
From the MySQL documentation:
If you specify ON DUPLICATE KEY UPDATE, and a row is inserted that would cause a duplicate value in a UNIQUE index or PRIMARY KEY, MySQL performs an UPDATE of the old row.
This approach doesn't only work with primary keys, it also works with any column having a unique index.
As Dan has mentioned, the ROW_COUNT() in-built function does not support this solution with a standard configuration.
MySQL::ROW_COUNT()
For UPDATE statements, the affected-rows value by default is the number of rows actually changed. If you specify the CLIENT_FOUND_ROWS flag to mysql_real_connect() when connecting to mysqld, the affected-rows value is the number of rows “found”; that is, matched by the WHERE clause.
If modifying the database schema is not an option, you could use the following method:
UPDATE `table` SET `country`='value1', `lastlogin`='value1' WHERE `email`='value3'
IF ROW_COUNT()=0
INSERT INTO `table` (`email`, `country`, `lastlogin`) VALUES ('value1', 'value2', 'value3')
you can use
$query=mysql_query("select * from table where email = 'your email'");
if(mysql_num_rows($query) > 0){
//update
}else{
//insert
}
You can load a row with the given email first and then decide if you have to insert or update depending on the existence of the loaded row. This needs multiple SQL statements, but it can be written in a DBMS vendor independent way. Use a surrounding transaction to handle concurrency. An index on the email-column is useful to keep the existence - check fast. Adding a unique - constraint on the email-column is an option to guarantee that there will never be multiple rows with same email.
You can do it manually like before inserting the value to table first check whether the value exists in table or not if yes then update your related field
$qry = mysql_query("select * from table where email='abc#abc.com'");
$count = mysql_num_rows($qry);
if($count > 0){
write your update query here
}else{
write your insert query here
}
I have a SQL query as follows-
"INSERT INTO users(id, rank) SELECT v.user, v.vote FROM votes v WHERE
v.assertion = '$ID' ON DUPLICATE KEY UPDATE
rank = ( CASE WHEN v.vote = '1' THEN rank+50 WHEN v.vote = '-1'
THEN rank-200 WHEN v.vote = '3' THEN rank+100 ELSE rank END)"
applied on a database with a table users with and id and rank field, and a votes table with a user and vote field. I have to update the rank of the users in the users table based on their vote.
I really like this kind of query, but I've noticed a problem: every time I execute this from my PHP script the query adds a row to the users table completely empty (with only an ID, which is A_I, and a rank of 1, when usually there would be other field as well). I can't really wrap my head around why this happens.
Any help/idea?
Your table does not have a primary key first provide a primary key to id
run this sql query
alter table user add primary key (id)
and than try it will work
There are two possible reasons :
The id column is not the primary key, and probably you table doesn't have a primary key at all.
Create a primary key like this :
alter table user add primary key (id)
If you insert an value of 0 in an auto increment column, a new id is generated. An auto incremented column must not contain the value 0.
There is also a more general problem with your approach : in fact you only insert the user id and the rank, other compulsory fields in the table (username) are missing. The insert part does not seem to be valid for this reason. If you use an insert on duplicate key update, you must make sure that the result is correct which ever of insert and update is executed.
I'm working on a CSV import script in PHP attached to a MySQL database. I want to give the users the option to either insert new rows if duplicates are found or update them.
I can't use ON DUPLICATE KEY UPDATE because the column cannot be unique, otherwise it won't cater for when they want to have duplicates.
How would I go about this?
Use 2 queries - a select query to determine if the row exists, then based on that result either an insert or update query.
I would script it for use on the command line. In your loop, check if an entry with the same key already exists. If it does, prompt the user to decide what to do using fgets(STDIN).
why not just add a UNIQUE key to the table, possibly spanning multiple fields?
here is an example given the following simple phonebook table:
CREATE TABLE phonebook (
firstname VARCHAR(255),
lastname VARCHAR(255),
home VARCHAR(50),
mobile VARCHAR(50)
)
you can easily add a key making firstname AND lastname together unique.
ALTER TABLE phonebook ADD UNIQUE (firstname, lastname)
that way you can use the ON DUPLICATE KEY UPDATE statement to easily update the phone numbers when the name is already on the list:
INSERT INTO phonebook (firstname, lastname, home, mobile)
VALUES ("john", "doe", "12345", "45678")
ON DUPLICATE KEY UPDATE home = "12345", mobile = "45678"
everything else is getting unnecessarily complex.
I'm creating a messaging system and I'm trying to set it up so it will have a "conversation view" and so users can reply to a message. To do this I have to have a primary ID for each conversation in the table and then a separate unique ID for each message.
My problem is that when I try replying to a message I get this error:
Duplicate entry '98' for key 1
It looks like it isn't allowing me to use the same ID in a column, but I don't have a 'unique' thing set in the table AFAIK.
I also tried to drop the PRIMARY for the id column but got this error:
The message is:
#1075 - Incorrect table definition; there can be only one auto column and it must be defined as a key
I don't understand why it won't let me insert the same ID into the id column, because as you know I need an ID for each conversation.
The mysql_query that I'm using to insert the reply into the table is:
$sql = "INSERT INTO messages (id, message_id, to_user, message, subject, from_user, date, time, date_short)
VALUES ('$id', '$message_id', '$to', '$message', '$subject', '$user', '$date', '$time', '$date_short')";
mysql_query($sql) or die(mysql_error());
Thanks in advance!
Your primary key can not be repeated, otherwise it isn't so useful as a key, is it? The primary key must uniquely identify the record.
The reason you're getting the error is that the column is set to be auto-number. You have not added that column to a separate key, which is a requirement for auto-number columns in MySQL.
Add it to a key/index with that column first, then remove the PK attribute. Make sure you have some PK in the table.
You can't have auto_increment without a key
I suspect you have AUTO_INCREMENT setup on your id field. If this is the case, then the values in the id column must be unique.
Either remove the AUTO_INCREMENT attribute on that column (by redefining the column without AUTO_INCREMENT via an ALTER TABLE command), or don't specify the id value in your INSERT statement.
First, untick AUTO_INCREMENT option on your column and as the second step, try to drop the index again
PRIMARY KEYs are also unique. auto_increment columns must be primary keys. You can't drop PRIMARY KEY from a column without making it not auto_increment.
However, I don't think you should change your table like this. You should keep your IDs and either create a new table with the data you need to update, or use UPDATE instead of INSERT.
Columns with primary keys can't have duplicates, otherwise they lose their uniqueness. MySQL will prevent same values. Having to alter primary key vales is also bad news. You may want to re-approach what you're doing and possibly create more tables.