代码之家  ›  专栏  ›  技术社区  ›  Max

用php添加mysql数据作为td属性

  •  0
  • Max  · 技术社区  · 7 年前

    我需要这段代码给我一个不同的输出。

     <?php
    
    $conn=mysqli_connect("localhost","root","","");
    
    if (mysqli_connect_errno())
      {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
      }
    
    
    function print_tableA ($conn, $id) {
        $sql = "SELECT Value1, Value2, Value3, Value4, Value5, Value6, Value7, Value8 FROM mytable1";
        $result = $conn->query($sql);
        if ($result->num_rows > 0) {
            echo "<table id='$id'>";
            while($row = $result->fetch_assoc()) {
                echo '<tr><td>' . join('</td><td>', $row) . "</td></tr>\n" ;
            }
            echo "</table>";
        }
    }  
    
    
    $result = $conn->query("SELECT Date from mytable2");
    while ($row = $result->fetch_assoc()) {
        print_tableA ($conn, $row['Date']);
    }
    
    ?>
    

    当前它以以下格式打印输出:`

    <tr>
    <td>2</td> 
    ....
    </tr>`
    

    我需要按以下格式打印:

    <tr>
    <td val="2">2</td>
    ....
    </tr>
    

    所以基本上,mysql中的数据也应该作为td属性重复。我希望这很简单,如果有人能告诉我需要做些什么才能得到这个结果,我会很感激的。谢谢。

    2 回复  |  直到 7 年前
        1
  •  1
  •   AndrewShmig    7 年前

    替换 while 与此循环:

    while($row = $result->fetch_assoc()) {
       $data = array_reduce($row, function($carry, $value) {
                   $carry[] = "<td val='{$value}'>{$value}</td>";
                   return $carry;
               }, []);
    
      echo '<tr>' . implode('', $data) . "</tr>\n" ;
    }
    

    将输出:

    <tr><td val='10'>10</td><td val='11'>11</td></tr>
    

    可以找到sendbox示例 here .

    php手册 array_reduce 功能。

        2
  •  1
  •   M. Eriksson    7 年前

    您需要遍历行值并根据需要回显td:

    while($row = $result->fetch_assoc()) {
        echo '<tr>';
    
        // Let's iterate through all the columns
        foreach ($row as $value) {
            echo "<td val='$value'>$value</td>";
        }
    
        echo "</tr>\n";
    }
    

    作为一个注释: val 不是中的有效属性 td -元素。