0

I am using below code to store data in table.

public function insert_pay_slip_data($data,$com_name)
    {

        $con = $this->__construct();
        $data = explode(',', $data[0]);
        foreach ($data as $value) 
            {
                $sql = "INSERT INTO `pay_slips`(`paye_id`, `trade_id`, `inv_pdf`, `created_date`, 
                `created_by`) VALUES (LAST_INSERT_ID(), '".$com_name."','".$value."',NOW(),'".$_SESSION['email']."')";
                $execute = mysqli_query($con, $sql);
                return $execute;
            }
    }

On print_r($data) i am getting all files that i am uploading from view:

Array ( [0] => 6650f7.pdf [1] => 34a3f.pdf [2] => 169512017.pdf )

I am getting this array in $data. So my concern is to store each file in different row with different primary keys.

But In for each loop $data only shows last uploaded file and in db only last file is inserted. Please help me to solve this issue.

amit sutar
  • 541
  • 2
  • 11
  • 37
  • In your foreach loop you have a return that will exit the function on the first iteration. Also, why do you call the constructor of your class to get a sql connexion ? – ᴄʀᴏᴢᴇᴛ Jun 20 '18 at 13:27
  • What do you mean by _"In for each loop $data only shows last uploaded file"_? – PajuranCodes Jun 20 '18 at 13:30
  • 1
    Please read http://bobby-tables.com/ and enlighten yourself as to why building parameterised SQL queries by concatenating strings is a bad idea – GordonM Jun 20 '18 at 13:55

2 Answers2

2
return $execute;

Are you aware that this exits the function after one row has been inserted? This terminates the loop.

Read http://php.net/return for documentation about the return statement in PHP.


This is not related to your problem of ending the loop early, but your code is insecure, it's vulnerable to SQL injection.

You should use query parameters instead of concatenating variables into your SQL statement. Read How can I prevent SQL injection in PHP? for more details on SQL injection.

Using query parameters is more secure and is actually easier to write the code than all those '".$value."' sequences.

Bill Karwin
  • 538,548
  • 86
  • 673
  • 828
0

You can try in single short like this:

$sql = "INSERT INTO `pay_slips`(`paye_id`, `trade_id`, `inv_pdf`, `created_date`, `created_by`) VALUES";
$i = 0;
foreach ($data as $value)
{
    if($i>0) {
        $sql .=",(LAST_INSERT_ID(), '".$com_name."','".$value."',NOW(),'".$_SESSION['email']."')"; 
    } else {
        $sql .="(LAST_INSERT_ID(), '".$com_name."','".$value."',NOW(),'".$_SESSION['email']."')";
    }
} 
$execute = mysqli_query($con, $sql);
return $execute;
er.irfankhan11
  • 1,280
  • 2
  • 16
  • 29