SQL inside For loop

Codes here !

Moderators: macek, egami, gesf

MikeSpider
New php-forum User
New php-forum User
Posts: 49
Joined: Sun Feb 05, 2012 12:48 pm

SQL inside For loop

Postby MikeSpider » Wed Nov 21, 2012 11:36 am

Hi guys,
Is it possible for something like this to work?

Code: Select all

<?php

 $Fcategories = array('Arts','Internet', 'Media','Music','traveling','TV Shows');                                       
                    for($i = 0; $i <  count($Fcategories); $i++){       
                   
                    $sql = "INSERT INTO forumCategories VALUES(NULL,'{$Fcategories[$i]}','{$_SESSION['forum_admin']}', NOW()";

                     $result = $this->db->mysqli->query($sql);         
                            if(!$result){ die("query failed! " . $sql . " - ". $this->db->mysqli->error);
                               }else{
                                   $this->success = true;
                               }
                        }                       
                   
?>


Any feedback is welcome,

Mike

MikeSpider
New php-forum User
New php-forum User
Posts: 49
Joined: Sun Feb 05, 2012 12:48 pm

Re: SQL inside For loop

Postby MikeSpider » Wed Nov 21, 2012 12:37 pm

OK I got it working!
it was missing a parenthesis.
Would this sort of technique harm my db in any way or my application?

Should I just use SQL concatenation like : INSERT INTO mytable VALUES(1,,5,3),(6,8,5).... ?

Mike

seandisanti
php-forum Fan User
php-forum Fan User
Posts: 838
Joined: Mon Oct 01, 2012 12:32 pm

Re: SQL inside For loop

Postby seandisanti » Fri Nov 23, 2012 2:56 pm

That's what I do typically, i'll start the string like

Code: Select all

$sql="INSERT INTO atable(field1,field2,field3) VALUES";

Then in my loop, just add the values...

Code: Select all

while ($row=mysqli_fetch_row($resultset)){
$sql .= "('" . $field1 . "','" . $field2 . "'," . $field3 . "),";
}
$sql = rtrim($sql,','); //to remove trailing comma after last concatenation.

and then execute it as one statement instead of doing an insert for each line


Return to “mySQL & php coding”

Who is online

Users browsing this forum: No registered users and 2 guests