MySQL查询中的PHP变量变量

时间:2012-10-09 08:55:46

标签: php mysql

此代码可以正常工作:$ batsman1name作为新值插入数据库中的正确行。

for($count = 1; $count <= 22; ++$count)
{
    $setbattingid = 'batsman' . $count . 'battingid';
    $$setbattingid = mysql_real_escape_string($_POST[$setbattingid]);
    $setname = "batsman" . $count . "name";
    $$setname = mysql_real_escape_string($_POST[$setname]);
    $query = "UPDATE batting_new SET batsmanname = NULLIF('$batsman1name', '') WHERE battingid = '$batsman1battingid'";
    $result = mysql_query($query);
    if (!$result) die ("Database access failed: " . mysql_error());
}

使用此代码,数据库不会更新,但可变变量$$ setname和$$ setbattingid包含与$ batsman1name和$ batsman1battingid相同的值。

for($count = 1; $count <= 22; ++$count)
{
    $setbattingid = 'batsman' . $count . 'battingid';
    $$setbattingid = mysql_real_escape_string($_POST[$setbattingid]);
    $setname = "batsman" . $count . "name";
    $$setname = mysql_real_escape_string($_POST[$setname]);
    $query = "UPDATE batting_new SET batsmanname = NULLIF('$$setname', '') WHERE battingid = '$$setbattingid'";
    $result = mysql_query($query);
    if (!$result) die ("Database access failed: " . mysql_error());
}

有什么想法吗?如果我没有很好地解释我的问题,请告诉我?感谢。

1 个答案:

答案 0 :(得分:1)

您应该使用:

$query = "UPDATE batting_new SET batsmanname = NULLIF('${$setname}', '') WHERE battingid = '${$setbattingid}'";

如下所述:http://php.net/manual/language.variables.variable.php