Concatenate for database field name

Hello
I am trying to put instead of “1” on the code below the value that is in the variable: $answer1
Basically answer1 is the column name in my database. $answer1 will hold a randomly generated number. Using this number that I need to append at the end I can get value from random fields.
How can I achieve this?

$row->answer1;

Tried this: $row->answer.+$answer1; but didnt work.

Thanks

I think you could do:

$vname = "answer" . $answer1; // assuming $answer1 contains the number
echo $row->$vname;

I don’t know if you can do it in line without creating the $vname variable.

Well, it doesn’t work because I have something like this:

$questionresults[3] = $row->answer1;

Something like this should work

<?php
error_reporting(E_ALL);
ini_set('display_errors', true);

$test_obj = (object) array(
			'first1' => "foo"
			,'first2' => "bar"
			,'first3' => "baz"
			);
$num_arr = array("1", "2", "3");
		
echo $test_obj->first1;	

foreach ($num_arr as $num) {
  $obj_prop = "first" . $num;							
  echo "<br />";
  echo $test_obj->$obj_prop;
}	
?>

outputs
foo
foo
bar
baz

this looks like the underlying problem is a non-normalised database. having column names like answer1, answer2, etc. indicate a one-to-many relationship for which you should use a separate table (and foreign keys).

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.