Ank
Ank

Reputation: 6270

Concat and Concat_ws in mysql

I have the following database structure.

ID | Name | Marks

I am trying to insert records in my PHP script. If the record doesn't exist, I'm creating a new record. If it does exist, I'm concatenating the marks column with the new marks.

$strSQL = "Replace into student set ID = '".$id."', 
                 name = '".$name."', marks= CONCAT_WS(',',Marks,'".$marks."')";

The query is running fine but concat is not working. The old record is being overwritten by the new one. I tried CONCAT too.

Thanks

Upvotes: 0

Views: 460

Answers (1)

Michael Berkowski
Michael Berkowski

Reputation: 270767

The proper way to handle this is with a separate normalized table holding student ids and marks. Use INSERT IGNORE to insert the student info in to the student table, and then insert the marks into the marks table, multiple rows per student. This also allows you to store a date along with each mark added to the table, or other information (like what course it belongs to). Note that I wouldn't usually recommend using INSERT IGNORE to create a row, but instead check first in code if the row exists and only insert if it doesn't.

CREATE TABLE marks (
   markID INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
   studentID INT NOT NULL,
   mark VARCHAR() NOT NULL,
   markdate DATETIME NOT NULL
);

/* First execute the insert, which will ignore errors if it already exists */
INSERT IGNORE INTO student (ID, name) VALUES ($id, '$name');

/* Then insert the new marks. Loop to add as many new marks as needed */
INSERT INTO marks (studentID, mark, markdate) VALUES ($id, '$marks', NOW());

Upvotes: 1

Related Questions