dpizd08264 2014-07-16 15:50
浏览 11

重新分解这个mysql表显示代码

I'm not wholly proficient with PHP but I'm having a few problems echoing a gathered value from a MySQL query function.

I believe I know where the problem lies but I'm not competent enough to fix it, if you could please help it would be appreciated.

PHP Function (Works perfectly).

<?php
$dbhost = 'localhost';
$dbuser = 'user';
$dbpass = 'password';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
    die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT Name, Role, Salary FROM `users-table`';

mysql_select_db('user_records');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
    die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
    echo "--------------------------------<br>",
         "Name: {$row['Name']}  <br> ".
         "Role: {$row['Role']} <br> ".
         "Salary : {$row['Salary']} <br> ".
         "--------------------------------<br>";
}
mysql_close($conn);
?>

This displays the data perfectly! However I'm now trying to include this in a nicely formatted HTML table. (Which is why I'm closing the php tag above).

I'm then trying to use a table like this:

<table >
        <tr>
            <td>
                <?php echo $row['Name'] ?>
            </td>
....

It outputs nothing, - I think this problem is caused because I close the first function and then try to reference $row and it doesn't know what to do...?

I think I need to tap in to while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) How can I re-factor this so that I can echo content from the above function to my table?

  • 写回答

2条回答 默认 最新

  • douwen1937 2014-07-16 15:57
    关注

    You didn't write the code you tried, but here is something functional:

    $link = mysqli_connect("myhost", "myuser", "mypassw", "mybd");
    echo "<table>";
    while ($row = mysqli_fetch_array($link, $retval, MYSQL_ASSOC)) {
        echo "
            <tr>
                <td>{$row['Name']}</td>
                <td>{$row['Role']}</td>
                <td>{$row['Salary']}</td>
            </tr>
        ";
    }
    echo "</table>";
    

    PS: Since MySQL is deprecated, I replaced your code with MySQLi, and I suggest you do the same :)

    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大