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.

3
  • 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 ? Commented Jun 20, 2018 at 13:27
  • What do you mean by "In for each loop $data only shows last uploaded file"? Commented Jun 20, 2018 at 13:30
  • 1
    Please read bobby-tables.com and enlighten yourself as to why building parameterised SQL queries by concatenating strings is a bad idea Commented Jun 20, 2018 at 13:55

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.