0

I have one table name "Grade" with this structure:

ID  Student_ID First_Name Last_Name Grade
1       1         John      Smith    60
2       2         Garry     Poul     70
3       1         John      Smith    80

And I want to add a new grade for Student_ID = 1 in the table Grade, I am using PHP with MySQL DB.

I used this but gives me error!

$sql = "INSERT INTO Grade (Grade) VALUES ('85') WHERE Student_ID=1 ";

During search I found that I can't use WHERE with INSERT in MySQL, how can solve it?

Thanks for all

M.Saeed
  • 303
  • 4
  • 14
  • You want to UPDATE and not INSERT – juergen d Nov 26 '21 at 06:18
  • This data is denormalised - the student names should be in s separate "students" table, not repeated in this grades table. This table only needs the student ID and grade fields...and maybe a subject ID - otherwise how do you know what the grade was for? – ADyson Nov 26 '21 at 06:54
  • Anyway are you asking how to add an extra grade for student 1, or alter one of the existing grades? It's not clear, from your wording. – ADyson Nov 26 '21 at 06:55
  • I want to add a new grade for the Student_ID in the same table. – M.Saeed Nov 26 '21 at 07:08
  • 2
    `insert into grade ( grade,student_id) values (85,1)`? – Professor Abronsius Nov 26 '21 at 07:19
  • 1
    Does this answer your question? [How to copy a row and insert in same table with a autoincrement field in MySQL?](https://stackoverflow.com/questions/9156340/how-to-copy-a-row-and-insert-in-same-table-with-a-autoincrement-field-in-mysql) – JMP Nov 26 '21 at 07:54

2 Answers2

1

For updating existing records use UPDATE and not INSERT

UPDATE Grade 
SET Grade = 85  
WHERE Student_ID = 1 
juergen d
  • 201,996
  • 37
  • 293
  • 362
  • But will update all ```Student_ID``` values in the table! and I want to add a new value not update – M.Saeed Nov 26 '21 at 07:13
-1

Insert: If you are adding values for all the columns of the table, you do not need to specify the column names in the SQL query

Update: when updating records in a table! Notice the WHERE clause in the UPDATE statement. The WHERE clause specifies which record(s) that should be updated. If you omit the WHERE clause, all records in the table will be updated!

UPDATE Grade SET Grade = 85 WHERE Student_ID=1 ;

  • 1
    INSERT does not have a WHERE clause, ever – ADyson Nov 26 '21 at 06:51
  • 1
    `you do not need to specify the column names in the SQL query`...you still should though, in case the order changes, or more fields are added in the middle of the list – ADyson Nov 26 '21 at 06:52
  • But I tried ```UPDATE``` it updated all Student_ID grades not added, I want to add not update. – M.Saeed Nov 26 '21 at 07:09