PHP将参数绑定到SQL查询并循环并打印结果

时间:2015-11-26 22:36:00

标签: php mysql

我在尝试打印SQL查询结果的html表时遇到了问题。

我目前有一个sql查询,需要一个' sid'它存储为局部变量。

我试图创建一个准备好的语句,它将$ sid var绑定到查询并创建一个while循环来遍历数据并将结果打印到表中。

下面,我尝试创建代码,但它似乎还没有起作用。 任何帮助,将不胜感激, 谢谢

$sid = '166410';

    $query =  "SELECT enrl.ayr, enrl.status, prog.ptitle, enrl.lvl
               FROM enrl, prog
               WHERE enrl.sid =?
               AND enrl.pid = prog.pid
               ORDER BY lvl DESC";

$scap = '';

if ($st = mysqli_prepare($link, $query)) {

    mysqli_stmt_execute($st);

    mysqli_stmt_bind_param($st, "s", $sid);

    mysqli_stmt_bind_result($st, $ayr, $status, $ptitle, $lvl);

    while (mysqli_stmt_fetch($st)) {
            $scap .= "
                  <table id=\"test\" style=\"width:100%\">
                      <tr>
                          <td> " . $ayr . " </td>
                          <td> " . $status . "</td>
                          <td> " . $ptitle . "</td>
                          <td> " . $lvl . "</td>
                      </tr>
                  </table>
              ";
            } $st->free();
        mysqli_stmt_close($st);
    }
    mysqli_close($link);

    print($scap);

1 个答案:

答案 0 :(得分:1)

<?php

$sid = '166410';
$query = "SELECT enrl.ayr, enrl.status, prog.ptitle, enrl.lvl
          FROM enrl, prog
          WHERE enrl.sid =?
          AND enrl.pid = prog.pid
          ORDER BY lvl DESC";
$scap = '';
$st = mysqli_prepare($link,$query);
mysqli_stmt_bind_param($st, "s", $sid);
mysqli_stmt_execute($st);
mysqli_stmt_bind_result($st, $ayr, $status, $ptitle, $lvl);
while (mysqli_stmt_fetch($st)) {
    $scap .= "
          <table id=\"test\" style=\"width:100%\">
              <tr>
                  <td> " . $ayr . " </td>
                  <td> " . $status . "</td>
                  <td> " . $ptitle . "</td>
                  <td> " . $lvl . "</td>
              </tr>
          </table>
          ";
}
echo $scap;
mysqli_stmt_close($st);
mysqli_close($link);
?>