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
Related
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.
Iam using a table in Mysql database and here there is a field called as First_Seen and Last_Seen and one of the field ID is marked as primary Key.
Now suppose my record is like this
12445555555|1|4444444855|2017-03-09 15:02:55|abc|134|M|SOME_RANDOM_NAME
Out of these 1244555555 field is made primary key.
SO if I try to insert this record into database it is inserting properly with both first_seen and last_seen as 2017-03-09 15:02:55.
But whenever the script executes the same command after 10 min (say) because the id is made primary key,the next record with different time like this is not inserted.
12445555555|1|4444444855|2017-03-09 15:12:55|abc|134|M|SOME_RANDOM_NAME
So all I wanted to do instead of inserting duplicate record into database I want to update the last_seen field.Any suggestions on this.Because even the script executes the same record n no of times it won't be reflected in database.
This is the db_insert.py script which takes the record from the csv file and extract the fields and insert into db
time = record[6]
try:
cursor = connection.cursor()
# Trying to create a new record
sql = "INSERT IGNORE INTO `my_table` (`ID`,`F1`,`F2`,`First_Seen`,`Last_Seen`,`F3`,`F4`,`F5`,`F6`) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)"
cursor.execute(sql,(id,f1,f2,time,time,f3,f4,f5,f6))
connection.commit()
finally:
connection.rollback()
connection.close()
All i wanted is whenever the duplicate entry occurs matching the id field then i need to replace the time with the time field in the current row and put it in last_seen.
This is what iam expecting.
12445555555|1|4444444855|2017-03-09 15:02:55|2017-03-09 15:12:55abc|134|M|SOME_RANDOM_NAME|something_else
Use ON DUPLICATE KEY UPDATE
INSERT INTO table (id, column1, column2)
VALUES(1, 'inserted value1', 'inserted value2') ON DUPLICATE KEY UPDATE column1="updated value 1", column2='updated value 2'
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.
Good evening ..
I am posting a form with values that include the number of the column in the data base (and not it's name) , so i want to update the field that the column name refers to,
here is my code :
$hours=$_POST['hour'];
$date=$_POST['date'];
$s=$_POST['subject'];
$res=mysql_query("UPDATE study SET [$s] ='$hours' WHERE day='$date' ");
Where $s is an integer that equals the number of the wanted column. But it doesnt work . so is there a way to refer to a column by it's number rather than it's name ?
According to This question, it seems you can only do that by using the information_schema table.
Add an autoincrement column that carries the unique number of the row to an existing table
ALTER TABLE mytable ADD idnum INT NOT NULL AUTO_INCREMENT;
(or add the field in a new table
CREATE TABLE mytable (
idnum INT NOT NULL AUTO_INCREMENT,
... )
And set idnum as PRIMARY KEY.
So that all rows have a unique number created by MySQL automatically. To insert a row, set the field to null and MySQL sets the number automatically
INSERT INTO mytable (idnum, ...) VALUES (null, ...);
Note that you can retrieve the idnum that MySQL set automatically thanks to PHP APIs, eg for mysqli (see this page),
$lastid = $mysqli->insert_id(); // $mysqli being the mysqli object
Then to update a value, you have to store somewhere (preferably in the session rather than on the page [since the user can modify it in this case - unless it doesn't matter])
// Modify field form
...SELECT idnum,nhours FROM mytable WHERE thedate = ...
$_SESSION['idnum'] = $row['idnum'];
...
// Display form ...
// Form processing
// Check first if SESSION has an idnum (an other parameters) in case the user hacked the page and submit a "special" form ...
/// Then
$res=mysql_query("UPDATE study SET nhours='$hours' WHERE idnum=" . $_SESSION['idnum']);
I have a table with 5 rows. Every time a user enters data into a form, it is entered into the table. My first column is called id and holds the number of the post. What I want to do is get the value of id from the previous row, add one to it and set it as the value in the current post's id field. How do I do this?
Just set that field as primary key and auto-increment, it will automatically do this for you. You won't have to fetch the previous row and add that field value to next one.
The SQL query you need is:
SELECT max(id)
FROM tableName;
Set attribute auto increment for "ID" field in the table that contains 5 columns.
You can use sql query like
"INSERT INTO my_table (id auto_increment,primary key(id))";
then you can get...
and eachtime you need not worry to insert id ,it will automatically increments
I would not recomend doing this as it could lead to a race condition.
Change the table structure and set the id field to be the primary key and set it to auto increment. This way anytime a new row is added, it will auto-magically be assigned the next ID.
see this answer on details of how to set auto increment.
here is the query to alter your table and it will set your field or column as primary key and also auto increment it.
ALTER TABLE tbl ADD id INT PRIMARY KEY AUTO_INCREMENT;