我想编写一个PHP函数,以特定的方式回显sql查询结果。

例子我有table 110.000 rows * 43 columns

NO NAME Prof Date of birth1 John Teacher 19872 Nick Engineer 1976345

等等。基于Nointeger(1-10.000),我想生成如下表:

Name: JohnProf: TeacherDate of birth: 1987

Name: NickProf: EngineerDate of birth: 1976

到目前为止,我的代码:

`
        

    $hostname = "";
    $username = "";
    $password = "";
    $dbname = "db1";

    //connection to the database
    $con = mysqli_connect($hostname, $username, $password, $dbname)
        or die("Unable to connect to MySQL");
    mysqli_set_charset($con, 'utf8');
    /*echo "Connected to db1 database <br>";
    else
    echo "Could not connect"; */

    $query1 = "SELECT * FROM `table 1` WHERE CODE_NO = 1";
    $query2 = "SHOW COLUMNS FROM table 1";
    $result1 = mysqli_query($con, $query1);
    $result2 = mysqli_query($con, $query2);

    // Check result
    // Useful for debugging.
     if (!$result1) {
        $message  = 'Invalid query: ' . mysqli_error($con) . "\n";
        $message .= 'Whole query: ' . $query1;
        die($message);
    }

    echo "<table>"; // table tag in the HTML
        while($row = mysqli_fetch_array($result1))
        //Creates a loop to loop through results
        {
        echo

        "<tr>
            <th>CODE_NO:</th>
            <td>" . $row['CODE_NO'] . "</td>
        </tr>
        <tr>
            <th>FIRST_NAME:</th>
            <td>" . $row['FIRST_NAME'] . "</td>
        </tr>
        <tr>
            <th>SURNAME:</th>
            <td>" . $row['SURNAME'] . "</td>
        </tr>
        <tr>
            <th>Date of birth:</th>
            <td>" . $row['DOB'] . "</td>
        </tr>
        <tr>
            <th>Date of death:</th>
            <td> " . $row['DOD'] . "</td>
        </tr>";
        }
    echo "</table>"; //Close the table in HTML

    ?>`


是否可以对过程进行一次编码而无需对任何事物进行硬编码,因此可以根据需要将其重复多次?

编辑:

$x = 1;$query = "SELECT * FROM个人WHERE CODE_NO = '$x'";$result = mysqli_query($con, $query);

最佳答案

如果我对您的理解正确,这将满足您的需求:

function generateTableFromResult($result) {
   $html = "<table>";
   while($row = mysqli_fetch_array($result)) {
      foreach($row as $column => $value) {
        $html.="<tr><th>".$column."</th><td>".$value."</td></tr>";
      }
   }
   $html.="</table>";
   return $html;
}

// usage:
// ...
$result1 = mysqli_query($con, $query1);
echo generateTableFromResult($result1);

10-08 06:31