将变量放入php变量echo中

时间:2013-07-04 02:21:58

标签: php php-5.3

这可能听起来很愚蠢,可能听起来不安全但是我的名字poke1hp中的列一直到poke6hp。我需要这样做,如果变量设置为1,它将选择并回显poke1hp列,如果变量为6,它将回显poke6hp

所以他就是我所得到的应该有效但不是。

if ($_SESSION['pickedslot'] == '1') {$tablename = "poke1hp";}
if ($_SESSION['pickedslot'] == '2') {$tablename = "poke2hp";}
if ($_SESSION['pickedslot'] == '3') {$tablename = "poke3hp";}
if ($_SESSION['pickedslot'] == '4') {$tablename = "poke4hp";}
if ($_SESSION['pickedslot'] == '5') {$tablename = "poke5hp";}
if ($_SESSION['pickedslot'] == '6') {$tablename = "poke6hp";}

我还使用$ tablename进行选择,此时我回显了$ tablename,并且所有工作正常,列名都在那里。现在我尝试在选择

中使用我在上面设置的变量的一侧使用列名
// here we grab the users hp 
$grabhp = $db->prepare("select '$tablename' from new_battles WHERE username = ?");
$grabhp ->execute(array($_SESSION['username']));
$grabhp2 = $grabhp ->fetch(); 

echo $grabhp2 ['$tablename'];

但我没有打印出任何内容......我知道不是有列我可以有行但我已经用这种方式编码了......

1 个答案:

答案 0 :(得分:0)

变量不会在单引号中展开:

http://php.net/manual/en/language.types.string.php

我建议不要在你的例子中使用引号。尝试:

echo $grabhp2[$tablename];

在您提供的示例中,您也错误地处理了MySQLi预处理语句。

以下是参考资料:

http://php.net/manual/en/mysqli.quickstart.prepared-statements.php