1

I have a string like this: $shortName = 'DATE,FB,DS,AK,GB,AJ,GL';

Now I want to create variables like $DATE $FB $DS $AK $GB $AJ $GL dynamically for passing these variables into bind_result() function.

here is my code

$gameQuery  = "SELECT `SHORT` FROM `game` WHERE `STATUS` = 1"
$gameStmt   =  $this->game->prepare($gameQuery);
$gameStmt   -> execute();
$gameStmt   -> bind_result($short);

$shortName = 'DATE';

while ($gameStmt->fetch()) {
   $shortName = $shortName.','.$short; 
}

echo $shortName; #output : DATE,FB,DS,AK,GB,AJ,GL

$chartQuery = "SELECT $shortName FROM `chart` WHERE MONTH(`date`) = ?";
$chartStmt  =  $this->chart->prepare($chartQuery);
$chartStmt  -> bind_param("s",$month);
$chartStmt  -> execute();
$chartStmt  -> bind_result();

Does anybody have a solution or an alternative for this ?

3
  • sorry but how ? $shortName store every $short and after while loop end i am using in other query .. Commented Apr 11, 2015 at 17:39
  • sorry my bad , any solution ? Commented Apr 11, 2015 at 17:41
  • 1
    any solution ? See the answers below maybe they answer your question Commented Apr 11, 2015 at 17:53

1 Answer 1

3

You can use extract() with explode() and array_combine() to do this:

$vars = explode(',', $shortName);
$array = array_combine($vars, $vars);
extract($vars);

Demo

explode() turn that string in an array using the comma as a separator. array_combine() creates an associative array with keys (needed for the next step). Then extract() turns each array element into a variable.

This feels convoluted but it is what you asked for.

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

1 Comment

Sorry but how can i use this variables in bind_result() function ?

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.