I'm trying to use this to insert the value "yes" into the list_title column where stream_number='3'. I can't figure out why it won't actually insert "yes" into the cell or any cell at all for that.
mysqli_query($con,"INSERT INTO livestreams (list_title) VALUE ('yes') WHERE stream_number='3'");
Heres the SQL i'm using to create the table if this helps
$createTable = "CREATE TABLE livestreams (stream_number INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(stream_number), stream_name CHAR(30), desired_username CHAR(30), stream_status CHAR(10), channel_description VARCHAR(300), game_name VARCHAR(100), viewer_count INT, list_title CHAR(30))";
What you're looking for is an UPDATE, not an INSERT. An INSERT adds new rows, while UPDATE changes something within existing rows.
UPDATE livestreams SET list_title = 'yes' WHERE stream_number = '3'
That SQL query should do.
INSERT inserts a new row into the table.
To update an existing row, use an UPDATE query.
Apparently you need to stop thinking in terms of Excel "cells". Databases work with rows a.k.a. records, and these records have fields. The datastore is not a 2D grid where you "insert" data into "cells"; even though it is often presented like that in the UI.
You should not use INSERT INTO with WHERE. Use UPDATE instead.
Related
I have a php script that logs inputs from a form into a mysql database table. I'm looking for a way to insert this data untill 3 rows are created, after which it has to update the existing rows so that the first one updates to the new input, the second one to the former first input and the third one to the former second input.
Table:
CREATE TABLE IF NOT EXISTS inputlog (
id int(11) NOT NULL auto_increment,
userid int(11) NOT NULL default '0',
name text,
value text,
PRIMARY KEY (id)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;`
For the first three rows i use:
insert into inputlog (userid,name,value) values('$userid','$name','$value')
After that is has to become:
update inputlog set value = '$value' where userid = '$userid' and name = '$name'
where it has to update all the successive rows.
How can i accomplish this?
Too long for comments, so...
Looks like you want to have only 3 rows in your table because you want the data to be sorted by the id. So id=1 will be the latest value, then id=2 and finally id=3.
In short, do not do that, the id field can be any value. Do not code for that. The danger is if you use the id in another table as a foreign key, you will loose referential integrity. What I propose is:
Add an timestamp column for each row.
Every time you insert a new value, set the timestamp column to NOW()
When selecting, sort on the timestamp and limit to 3 results
If you MUST have only 3 rows, you can then delete the row except for the 3 most recent timestamps.
But... if you must do that...
perform a SELECT with the first 2 lines
truncate the table (delete all rows)
insert the new line, then the 2 stored lines
You will then ahve your 3 rows in the order you want. But without seeing the entire reasoning for your application, my "spider sense" tells me you will hit a wall later on...
And check the comments for other things to worry about.
Good day guys, I have a grade/score table in MySql that students record will be inserted into using php. I want to avoid a student having a score repeated for a term/period. What I mean is that a student cant have two(2) grades/scores for a subject(mathematics) in a term(periodOne) table. How do I accomplish this in MySql or php? here is how my table looks:
table periodOne (
id int AUTO_INCREMENT,
studentId int,
subjectId int,
score
)
Let me know if you need extra information. Thanks!!!!!!
you have to add a unique contraint in mysql like this : ALTER TABLE periodOne ADD CONSTRAINT uc_check UNIQUE(studentId, subjectId). You will also have to check with PHP that there is no existing row before to do your INSERT
You can declare the attribute as "Unique" by using UNIQUE CONSTRAINT for which you don't want duplicate value.
If your score are dependent on some other table also then you can use Composite Primary Key.
I am trying to insert into a column if the column value is not null.
I have my table:
create table clock(
usr_id int,
clock_id int AUTO_INCREMENT,
clock_in date,
clock_in_time time,
clock_out date,
clock_out_time time,
FOREIGN KEY (usr_id)references df_user(usr_id),
primary key(clock_id)
);
I am trying to grab the last entry of the table and checking whether or not it is null.
SET #lastEntry = (SELECT clock_id FROM clock WHERE clock_id=(SELECT max(clock_id) FROM clock));
SET #clock_value = (select clock_out from clock where clock.clock_id = #lastEntry);
If the last entries clock out column is NULL (#clock_value IS NULL) then insert into the table.
if #clock_value IS NULL THEN insert into clock (clock_out, clock_out_time) values (curdate(), curtime());
Can someone please tell me the correct way of doing this process? SQL is telling me that the query is wrong. Thanks all!
What you need seems to be an update clause.
update clock set clock_out=curdate(), clock_out_time=curtime() ;
or something like that. You cannot insert here, because when inserting you create new rows.
I'm creating a change log db that's the exact same as my active db except it has a changedate DATE field at the end.
The db is basically one primary key id, and about 50 other columns of various data types. The script I have in php is it tries to insert new ids and if it gets the error message for duplicate primary key, then it should get that row, insert it into my backup db with a curdate() call as the final date value, delete the entry from my first db, then insert the new entry.
I have all the other parts of the script finished except the part where I have to insert everything from the first table + an extra column for curdate(). Or if there's a better solution to my problem of inserting into a backup database when a duplicate primary key comes in when there's a fairly high amount of rows please share that.
You could do an INSERT INTO SELECT:
INSERT INTO `backupTable` SELECT *, NOW() FROM `originalTable` WHERE id = '$id';
You have to specify the ID for the entry you wish to copy to your backup db. You have also to be sure, that the IDis not already in your backup table. You can use REPLACE INTO to workaround this case.
REPLACE INTO `backupTable` SELECT *, NOW() FROM `originalTable` WHERE id = '$id';
basicly, you can create a TIMESTAMP column with CURRENT_TIMESTAMP as default value.
when you insert a row to that table, the current date/time will be automaticly inserted.
is that what you were looking for ?
BTW: i would recommend to kill the problem at it source and make sure a duplicate primary key will not be inserted to the datatable..
to do that, you can use the SELECT LAST_INSERT_ID();
I asked this question a little earlier today but am not sure as to how clear I was.
I have a MySQL column filled with ordered numbers 1-56. These numbers were generated by my PHP script, not by auto_increment.
What I'd like to do is make this column auto_incrementing after the PHP script sets the proper numbers. The PHP script works hand in hand with a jQuery interface that allows me to reorder a list of items using jQuery's UI plugin.
Once I decide what order I'd like the entries in, I'd like for the column to be set to auto increment, such that if i were to insert a new entry, it would recognize the highest number already existing in the column and set its own id number to be one higher than what's already existing.
Does anyone have any suggestions on how to approach this scenario?
I'd suggest creating the table with your auto_increment already in place. You can specify a value for the auto_inc column, and mysql will use it, and still the next insert to specify a NULL or 0 value for the auto_inc column will magically get $highest + 1 assigned to it.
example:
mysql> create table foobar (i int auto_increment primary key);
mysql> insert into foobar values (10),(25);
mysql> insert into foobar values (null);
mysql> select * from foobar;
# returns 10,25,26
You can switch it to MySQL's auto_increment implementation, but it'll take 3 queries to do it:
a) ALTER TABLE to add the auto_increment to the field in question
b) SELECT MAX(id) + 1 to find out what you need to set the ID to
c) ALTER TABLE table AUTO_INCREMENT =result from (b)
MySQL considers altering the AUTO_INCREMENT value a table-level action, so you can't do it in (a), and it doesn't allow you to do MAX(id) in (c), so 3 queries.
You can change that with a query, issued through php, using the mysql console interface or (easiest) using phpmyadmin.
ALTER TABLE table_name CHANGE old_column_name new_column_name column_definition;
ALTER TABLE table_name AUTO_INCREMENT = highest_current_index + 1
column_definiton:
old_column_definition AUTO_INCREMENT
More info:
http://dev.mysql.com/doc/refman/5.1/en/alter-table.html
http://dev.mysql.com/doc/refman/5.1/en/create-table.html
EDIT
Always use mysql_insert_id or the appropiate function of your abstraction layer to get the last created id, as LAST_INSERT_ID may lead to wrong results.
No, stop it. This isn't the point of auto_increment. If you aren't going to make them ordered by the id then don't make them auto_increment, just add a column onto the end of the table for ordering and enjoy the added flexibility it gives you. It seems like you're trying to pack two different sets of information into one column and it's really only going to bite you in the ass despite all the well-meaning people in this thread telling you how to go about shooting yourself in the foot.
In MySQL you can set a custom value for an auto_increment field. MySQL will then use the highest auto_increment column value for new rows, essentially MAX(id)+1. This means you can effectively reserve a range of IDs for custom use. For instance:
CREATE TABLE mytable (
id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
col1 VARCHAR(256)
);
ALTER TABLE mytable AUTO_INCREMENT = 5001;
In this schema all ids < 5001 are reserved for use by your system. So, your PHP script can auto-generate values:
for ($i=1; $i<=56; $i++)
mysql_query("INSERT INTO mytable SET id = $i, col1= 'whatevers'");
New entries will use the non-reserved range by not specifying id or setting it to null:
INSERT INTO mytable SET id = NULL, col1 = 'whatevers2';
-- The id of the new row will be 5001
Reserving a range like this is key - in case you need more than 56 special/system rows in the future.
ALTER TABLE <table name> <column name> NOT NULL AUTO_INCREMENT
More info:
AUTO_INCREMENT Handling in InnoDB
Server SQL Modes