简体   繁体   中英

I want to get a value from database and then increment it to use in insert query

I am getting the result from the select query but when i try to increment the value of $slot and then insert in my table 2 rows are added i want to add only 1 row with the incremented value of slot.

Here is my code

       try{
 $slot_query="Select max(slot) AS maxslot from mdl_quiz_slots where quizid=$quiid";
     $queryResult=db_query($slot_query);
     foreach ($queryResult as $row) {
 $slot=$row->maxslot;
 $slot++;
 $question_query ="INSERT INTO mdl_quiz_slots ".
   "(slot,quizid,page,requireprevious,questionid,maxmark)".
   "VALUES ".
   "('$slot','$quiid','$page','$requireprevious','$questid','$maxmark')";
    $queryResult=db_query($question_query);

    }

I'm not seriously advocating this as a solution, but here's something you can play with anyway...

CREATE TABLE my_table (i INT NOT NULL UNIQUE);

INSERT INTO my_table SELECT COALESCE(MAX(i)+1,1) FROM (SELECT 1) x, my_table LIMIT 1;

SELECT * FROM my_table;
+---+
| i |
+---+
| 1 |
+---+

INSERT INTO my_table SELECT COALESCE(MAX(i)+1,1) FROM (SELECT 1) x, my_table LIMIT 1;
Query OK, 1 row affected (0.00 sec)
Records: 1  Duplicates: 0  Warnings: 0

SELECT * FROM my_table;
+---+
| i |
+---+
| 1 |
| 2 |
+---+
2 rows in set (0.00 sec)

I don't know if there's enough information here to solve, because I get the feeling you're calling this whole try snippet twice.

Because you're calling a select max query, I expect only one result, but not sure what's happening inside your custom database wrapper class. So you might try to move your insert statement outside the loop

try{
 $slot_query="Select max(slot) AS maxslot from mdl_quiz_slots where quizid=$quiid";
 $queryResult=db_query($slot_query);
 foreach ($queryResult as $row) {
   $slot=$row->maxslot;
   $slot++;
 }

$question_query ="
INSERT INTO mdl_quiz_slots 
(slot,quizid,page,requireprevious,questionid,maxmark)
VALUES
('$slot','$quiid','$page','$requireprevious','$questid','$maxmark');
";
$queryResult=db_query($question_query);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM