在SQL查询中使用PHP变量变量

时间:2021-03-11 00:06:11

Sorry for this question to be a "can you fix it" one, but this little bit of code has been confusing me for a while now.

很抱歉这个问题是“你可以解决它”吗,但这一小段代码让我困惑了一段时间。

I'm basically making a table with a bunch of rows and columns and in each one I have a slightly changing SQL query. To make it a bit easier instead of typing all that out I made this bit of script but it is starting to get a bit complicated so can any of you manage to get it correct?

我基本上是用一堆行和列创建一个表,每一个我都有一个稍微改变的SQL查询。为了使它更容易,而不是输入所有这些,我做了这个脚本但是它开始变得有点复杂,所以你们中的任何人都能设法让它正确吗?

echo '<td background="images/map/';
$tile = mysql_fetch_array(mysql_query("SELECT image FROM map WHERE horizontal = ${'mapPiece' . $mapPieceCount . [0]} AND verticle = ${'mapPiece' . $mapPieceCount . [0]}"));
echo $tile[0];
echo '.png"></td>';

Thanks, Stanni

2 个解决方案

#1


Assuming I interpreted this right, the [0] needs to go outside of the curly braces:

假设我解释正确,[0]需要超出花括号:

echo '<td background="images/map/';
$tile = mysql_fetch_array(
          mysql_query(
            "SELECT image FROM map WHERE horizontal = ".
            ${'mapPiece' . $mapPieceCount}[0].
            " AND verticle = ".
            ${'mapPiece' . $mapPieceCount}[0]
          )
        );
echo $tile[0]; 
echo '.png"></td>';

#2


First of all, you can't append the array index [0] like that, like you're concatenating on a string. Overall, it would be much easier if you just added a few extra lines to make things neater:

首先,你不能像这样连接数组索引[0],就像你在字符串上连接一样。总的来说,如果你只是添加一些额外的线条以使整洁的东西更容易:

$currentPiece = 'mapPiece' . $mapPieceCount;
echo '<td background="images/map/';

$query = 'SELECT image '.
            'FROM map '.
            'WHERE horizontal = '.${$currentPiece}[0].' '.
                'AND verticle = '.${$currentPiece}[0];
$result = mysql_query($query);
$tile = mysql_fetch_array($result);

echo $tile[0];
echo '.png"></td>';

#1


Assuming I interpreted this right, the [0] needs to go outside of the curly braces:

假设我解释正确,[0]需要超出花括号:

echo '<td background="images/map/';
$tile = mysql_fetch_array(
          mysql_query(
            "SELECT image FROM map WHERE horizontal = ".
            ${'mapPiece' . $mapPieceCount}[0].
            " AND verticle = ".
            ${'mapPiece' . $mapPieceCount}[0]
          )
        );
echo $tile[0]; 
echo '.png"></td>';

#2


First of all, you can't append the array index [0] like that, like you're concatenating on a string. Overall, it would be much easier if you just added a few extra lines to make things neater:

首先,你不能像这样连接数组索引[0],就像你在字符串上连接一样。总的来说,如果你只是添加一些额外的线条以使整洁的东西更容易:

$currentPiece = 'mapPiece' . $mapPieceCount;
echo '<td background="images/map/';

$query = 'SELECT image '.
            'FROM map '.
            'WHERE horizontal = '.${$currentPiece}[0].' '.
                'AND verticle = '.${$currentPiece}[0];
$result = mysql_query($query);
$tile = mysql_fetch_array($result);

echo $tile[0];
echo '.png"></td>';