-1

I have a Quiz module in which I have two tables quiz_question and quiz_options. quiz_question is saving Questions and quiz_option saving options for particular questions.

table structure for quiz_option: id | question_id | text | is_correct

table structure for quiz_question id | title | desctiption |

Where question_id is foreign key to id of quiz_question

I want to write a query to update quiz_question and all its corresponding quiz_options is a single query.

enter image description here

Al Foиce ѫ
  • 4,195
  • 12
  • 39
  • 49

4 Answers4

0

Multiple table update you can use foreign key connect two and more table with foreign key concept update parent table primary key to child table foreign key see link http://www.hostingadvice.com/how-to/mysql-foreign-key-example/.

table quiz_question PK (question_id)
table quiz_option FK (question_id)
pawan sen
  • 716
  • 5
  • 14
0

Get the id of the question and Update them one by one as you cannot update two tables using a single query.

$ID_VALUE = mysqli_real_escape_string($conn, $_GET['id']);
UPDATE quiz_option SET fields_name = 'value' WHERE question_id = $ID_VALUE;
UPDATE quiz_question SET fields_name = 'value' WHERE id = $ID_VALUE;
VishalParkash
  • 490
  • 3
  • 15
  • 1
    [Little Bobby](http://bobby-tables.com/) says ***[your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php)*** Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php). Even [escaping the string](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) is not safe! [Don't believe it?](http://stackoverflow.com/q/38297105/1011527) Please do not teach bad coding habits. – Jay Blanchard Oct 17 '16 at 13:09
  • He/she seems like a beginner to me so helped him/her with easy answer. – VishalParkash Oct 17 '16 at 13:14
  • Alright.. My mistake once again. :) I will careful next time – VishalParkash Oct 17 '16 at 13:18
0

Here is the query:

INSERT INTO quiz_question(title,description) VALUES ('test','test question'); 
INSERT INTO quiz_option(question_id,text,is_correct) VALUES (LAST_INSERT_ID(),'test','0'),(LAST_INSERT_ID(),'test2','0'),(LAST_INSERT_ID(),'test3','0'),(LAST_INSERT_ID(),'test4','1')
-1

try this

UPDATE  table1 a
        INNER JOIN table2 b
            ON a.ID = b.ID
SET     a.value = b.value 
mhmd
  • 254
  • 2
  • 3
  • 14
  • 1
    @ArditMeti the [documentation](http://dev.mysql.com/doc/refman/5.5/en/update.html) disagrees – apokryfos Oct 10 '16 at 12:57
  • 1
    @ArditMeti http://stackoverflow.com/questions/4361774/mysql-update-multiple-tables-with-one-query – mhmd Oct 10 '16 at 12:58