0

Query with Variable Arguments take only first one

I tried to echo all Variable Arguments from foreach loop ant It works, but when I Type query it only done on the first Argument

function SelectDB($Table,$Stm,$Value,...$Selectors){
global $conn;
foreach($Selectors as $Selector){
  //That works and echo all Selectors
  echo $Selector; 
 } 
 }
function SelectDB($Table,$Stm,$Value,...$Selectors){
  global $conn;
   foreach($Selectors as $Selector){
  //Only First Selector is executed in Query
  $Query = $conn->prepare("SELECT $Selector FROM $Table WHERE $Stm = ?");
  $Query->execute(array($Value)); 
  $Fetch = $Query->fetch();
  return $Fetch;
   } 
 }
$S = SelectDB("attended","Id",1,"Id","s","Date","TeacherId");
echo $S['TeacherId']; //Undefined Index
echo $S['Id']; //echo The Id 

I Want to execute query for every selector

1
  • 2
    Because you don't understand what return does. Commented Jun 2, 2019 at 8:33

1 Answer 1

1

You use return statement in your loop, so it will return at the first iteration.

Use a buffer to store data, and return it :

function SelectDB($Table,$Stm,$Value,...$Selectors) {
  global $conn;
  $result = [];
  foreach($Selectors as $Selector) {
    //Only First Selector is executed in Query
    $Query = $conn->prepare("SELECT $Selector FROM $Table WHERE $Stm = ?");
    $Query->execute(array($Value)); 

    // push fetch to result
    $result []= $Query->fetch();
 }

 return $result;
}
Sign up to request clarification or add additional context in comments.

1 Comment

I tried to echo the fetch data and it worked but it give same index error when i store them in array and return the array

Your Answer

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