-1

This is my function with a foreach:

$InsertData = function($getQuery) use($localLink, $tableTelephoneNumber)
{
  $data = GetData($getQuery);  

  foreach ($data['data'] as $value)
  { 
    $insertQuery = "INSERT INTO $tableTelephoneNumber (TelephoneNumber, DeliveryContractId) VALUES ('$value->Number__c','". $value->DeliveryContract__r->Id ."')";
    mysqli_query($localLink, $insertQuery);
  }
}

As you can see i use $value in my $insertQuery variable. The problem i have is that i want to declare and pass $insertQuery to the function from outside but i want it to keep using $value which is inside the foreach. Is this possible in PHP 7?

Neavehni
  • 337
  • 1
  • 2
  • 14
  • Your script is open to [SQL Injection Attack](http://stackoverflow.com/questions/60174). Even [if you are escaping inputs, its not safe!](http://stackoverflow.com/questions/5741187) You should consider using [prepared parameterized statements](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) in either the `MYSQLI_` or `PDO` API's instead of concatenated values – RiggsFolly Dec 17 '20 at 11:51
  • 3
    Yes, if you switch to [parametrized queries](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php), because then the values to be inserted are sent separately from the query. And will make your code safer. – El_Vanja Dec 17 '20 at 11:52
  • kindly elaborate your question briefly! – Hammad Ahmed khan Dec 17 '20 at 11:52
  • I would go with PDO and prepare array and batch insert. Here's example: https://phpdelusions.net/pdo_examples/insert#multiple – cssBlaster21895 Dec 17 '20 at 11:55

1 Answers1

0

If you prepare the query and then pass the prepared statement into the function it would work quote nicely and be more secure against SQL Injections.


$iQ = "INSERT INTO `$tableTelephoneNumber` (`TelephoneNumber`, `DeliveryContractId`) VALUES (?,?)";
$PrepedQuery = $localLink->prepare($iQ);

$InsertData = function($getQuery) use($localLink, $tableTelephoneNumber, $PrepedQuery ) {
    $data = GetData($getQuery);  
    foreach ($data['data'] as $value){ 
        $PrepedQuery->bind_param('si', $value->Number__c, $value->DeliveryContract__r->Id);
        $PrepedQuery->execute();
    }
}
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149