Search code examples
phpmysqlfor-loopprepared-statement

How can i execute a prepared SQL statement multiple times inside a FOR loop ?


I want to insert multiple rows to my table using prepared statements, And for that matter i use loops to extract data from an Array and use it for y statement parameters, Here's my code sample :

require_once("connect.php");
$data_array = Array();
$string = 'faycal,18,12,2016,podes|Arab,19,12,2016,kashi|faycal,20,12,2016,exec';
function create_array($input){
    $formated_array = explode('|', $input);
    $query = $con->prepare("INSERT INTO my_table (bill_name,bill_num,month,year,type) VALUES(?, ?, ?, ?, ?)");
        for ($i = 0;$i < count($formated_array);$i++){
            for($j = 0;$j < 5;$j++){
                $data_array[$i][$j] = explode(',', $formated_array[$i])[$j];
            }
            $query->bind_param($name, $num, $month, $year, $type);
            $name =  $data_array[$i][0];
            $num = (int)$data_array[$i][1];
            $month = (int)$data_array[$i][2];
            $year = (int)$data_array[$i][3];
            $type = $data_array[$i][4];

            $query->execute();
        }   
        echo "Records have been saved successfully";

}
create_array($string);

I've tested this function without executing the statement and tried to echo data_array, Everything worked perfectly So I'm assuming there's something wrong with my SQL statements which i can't figure out.


Solution

  • SCOPE, Scope, scope The $con variable is not visible inside the function by default. SO pass it into the function as a parameter.

    function create_array($con, $input){
        $query = $con->prepare("INSERT INTO my_table
                                      (bill_name,bill_num,month,year,type) 
                                VALUES(?, ?, ?, ?, ?)");
        // ... the rest of your function body ...
    }
    
    require_once("connect.php");
    $string = 'faycal,18,12,2016,podes|Arab,19,12,2016,kashi|faycal,20,12,2016,exec';
    create_array($con, $string);