Thread: Foreach insert

    #1
  1. Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Oct 2005
    Posts
    650
    Rep Power
    20

    Foreach insert


    Hey guys i have tried a few combos but no success

    i have a script that i did that parses an m3u file

    it works and also tried to insert the data in mysql DB

    so parsing part is good:

    PHP Code:
    $file 'tv_plus.m3u';
    $content file_get_contents$file ); 
    $pattern '#tvg-logo="([^"]*)" group-title="([^"]*)",([^\r\n]*)\r\n#Ui';
    if( 
    $result )
    {
        
    $result_formatte = array();
        foreach( 
    $matches[1] as $i => $val )
        {
            
    $result_formatte[] = $matches[2][$i].' - '.$matches[3][$i].' | '.$matches[1][$i]; 
        }
        echo 
    implode($result_formatte'<br>');

    //1=logo
    //2=group-title
    //3 =tvg-name

    The only way i found to insert is one by one...

    PHP Code:
    $result_formatte = array();
        foreach( 
    $matches[1] as $i => $val )
        {        
            
    $result_formatte[] = $matches[1][$i];
        }
    foreach( 
    $result_formatte as $ligne )
        {
            
    $result2 mysqli_query($DBcon"INSERT INTO Channels (Logo) VALUES ('$ligne')");
        }
    and 
    then same but $matches[2][$i];

    and 
    same for $matches[3][$i]; 
    It works..But it inserts in different lines..so i have about 600 entries cause one is for [1] then it enters [2]...

    how can i insert all the information in one time..

    thx!
  2. #2
  3. Wiser? Not exactly.
    Devshed God 2nd Plane (6000 - 6499 posts)

    Join Date
    May 2001
    Location
    Bonita Springs, FL
    Posts
    6,270
    Rep Power
    4193
    Specify all your columns in your insert query. You can get your other values by referencing the other indexes when you loop.

    You also need to use prepared statements and bound parameters to avoid SQL Injection issues.
    Code:
    //Prepare query with placeholders for values.
    $stmt = mysqli_prepare($DBcon, 'INSERT INTO Channels (Logo, Group, TVG) VALUES (?, ?, ?)');
    mysqli_stmt_bind_param($stmt, 'sss', $logo, $group, $tvg);
    
    foreach(array_keys($matches[1]) as $i)
    {
        $logo = $matches[1][$i];
        $group = $matches[2][$i];
        $tvg = $matches[3][$i];
    
        //Run the query with current values of $logo, $group, and $tvg
        mysqli_stmt_execute($stmt);
    }

    Comments on this post

    • techker agrees : props
    Recycle your old CD's



    If I helped you out, show some love with some reputation, or tip with Bitcoins to 1N645HfYf63UbcvxajLKiSKpYHAq2Zxud
  4. #3
  5. Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Oct 2005
    Posts
    650
    Rep Power
    20
    Props man! works great.i have been messing around with that for a few hours...uhh

IMN logo majestic logo threadwatch logo seochat tools logo