Reputation: 6752
I have an INSERT loop and I need to add a reference number to it. I need all of the reference numbers in the loop to be the same. I know that with MAX() I can select the highest number in the table. But if I loop it will just increase with each loop while I need it to stay the same.
Is there a way of doing this in the query itself? Or is the only way to save it in a variable outside of the loop?
Example code:
for($i=2;$i<=$row_count;$i++){ // Loops 3 times (example)
$part = $vehicle.'_part'.$i;
$description = $vehicle.'_description'.$i;
$imageName = $vehicle.'_image'.$i;
$parts[] = array(
'part' => $_SESSION[$part],
'image' => $_SESSION[$part],
'description' => $_SESSION[$description]);
}
foreach($parts as $onePart){
$queries[] = "INSERT INTO searches_tbl (ref_nr, vozila_id, korisnici_id, part, description, image)
VALUES (???, (SELECT id FROM vozila_tbl ORDER BY id DESC LIMIT 1),
(SELECT id FROM korisnici_tbl WHERE email = '".$email_address."' ORDER BY id DESC LIMIT 1), '".$onePart['part']."', '".$onePart['description']."', '".$onePart['image']."')";
}
Upvotes: 0
Views: 157
Reputation: 156
You can create a new table, ie searches_ref
with just an AUTO_INCREMENT Primary Key-column.
CREATE TABLE
searches_ref
(id
INT NOT NULL AUTO_INCREMENT PRIMARY KEY );
You would then insert a new line in searches_ref
before the loop, and get a new id you can use in the loop.
This way, you should not have concurrency issues (which you will probably get using MAX()
)
Upvotes: 1