如何将字符串转换为变量以在服务器代码中使用

时间:2013-12-18 17:17:24

标签: php mysql sql

我希望将$ RowNumber从字符串转换为变量,以便在while中使用,那可能吗?!怎么做?

$row1 = mysqli_query($Database,"SELECT * FROM Table1 ORDER BY ID");
$row2 = mysqli_query($Database,"SELECT * FROM Table2 ORDER BY ID");
// Others Rows code

for ($num = 1; $num <= 6; $num++)
{
  $RowNumber = "row" . $num;   // Save RowNumber for use in while

  echo '<tr>';
  // when it's used it not work becuse it's just a string only and 
  // i want convert it to variable to use in while
  while($row = mysqli_fetch_array($RowNumber)) 
  {
    echo  '<td>
        <div class="Image_DIV" id="'; echo $row['DIV_ID'];  echo  '">
          <table>
            <tr><td class="Image"><img class="ImageOfDiv" 
              src="3DGallery/Chosen/Small/'; echo $row['src']; echo '"/></td></tr>
            <tr>
              <td class="ImageDescribe">'; echo $row['describe']; echo '</td></tr></table>
        </div>
        </td>';
   }
   echo '</tr><tr>';
}

3 个答案:

答案 0 :(得分:1)

尝试使用${$RowNumber}代替$ RowNumber,如果您需要更多信息,可以找到它here。但正如raina77ow先生所评论的阵列是一个不错的选择。

答案 1 :(得分:0)

试试这个:

$rows[] = mysqli_query($Database,"SELECT * FROM Table1 ORDER BY ID");
$rows[] =  mysqli_query($Database,"SELECT * FROM Table2 ORDER BY ID");
// Others Rows code

foreach ($rows as $current)
{

  echo '<tr>';
  // loop the query
  while($row = mysqli_fetch_array($current)) 
  {
    echo  '<td>
        <div class="Image_DIV" id="'; echo $row['DIV_ID'];  echo  '">
          <table>
            <tr><td class="Image"><img class="ImageOfDiv" 
              src="3DGallery/Chosen/Small/'; echo $row['src']; echo '"/></td></tr>
            <tr>
              <td class="ImageDescribe">'; echo $row['describe']; echo '</td></tr></table>
        </div>
        </td>';
   }
   echo '</tr><tr>';
}

你不能在不使用php Eval:http://www.php.net/eval的情况下分配这样的变量,但这实际上是不好的做法!

或使用$ {$ var}语法。但阵列可能更容易使用。

答案 2 :(得分:0)

如果Table1Table2具有相同的列,那么您应该在SQL中UNION将它们放在一起,然后处理单个结果集。

$results = mysqli_query($Database, "SELECT ID, DIV_ID, src, describe FROM `Table1` UNION SELECT ID, DIV_ID, src, describe FROM `Table2` ORDER BY ID");

echo '<tr>';
$x = 0;
while($row = mysqli_fetch_array($results))
{
    echo '<td>';
    echo $row['DIV_ID'];
    echo $row['src'];
    echo $row['describe'];
    echo '</td>';
    if( ++$x % 3 == 0 ) {
        echo '</tr><tr>';
    }
}
echo '</tr>';