Ryan
Ryan

Reputation: 339

Using PHP variable variables in SQL query

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?

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

Upvotes: 0

Views: 3687

Answers (2)

Chad Birch
Chad Birch

Reputation: 74518

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:

$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>';

Upvotes: 4

Jeremy Stanley
Jeremy Stanley

Reputation: 5926

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

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>';

Upvotes: 5

Related Questions