How to echo out table rows from the db (php)

前端 未结 5 1196
故里飘歌
故里飘歌 2020-11-28 11:35

i want to echo out everything from a particular query. If echo $res I only get one of the strings. If I change the 2nd mysql_result argument I can get the 2nd, 2rd etc but

5条回答
  •  庸人自扰
    2020-11-28 11:59

    Expanding on the accepted answer:

    function mysql_query_or_die($query) {
        $result = mysql_query($query);
        if ($result)
            return $result;
        else {
            $err = mysql_error();
            die("
    {$query}
    *** {$err} ***
    "); } } ... $query = "SELECT * FROM my_table"; $result = mysql_query_or_die($query); echo(""); $first_row = true; while ($row = mysql_fetch_assoc($result)) { if ($first_row) { $first_row = false; // Output header row from keys. echo ''; foreach($row as $key => $field) { echo ''; } echo ''; } echo ''; foreach($row as $key => $field) { echo ''; } echo ''; } echo("
    ' . htmlspecialchars($key) . '
    ' . htmlspecialchars($field) . '
    ");

    Benefits:

    • Using mysql_fetch_assoc (instead of mysql_fetch_array with no 2nd parameter to specify type), we avoid getting each field twice, once for a numeric index (0, 1, 2, ..), and a second time for the associative key.

    • Shows field names as a header row of table.

    • Shows how to get both column name ($key) and value ($field) for each field, as iterate over the fields of a row.

    • Wrapped in

      so displays properly.

    • (OPTIONAL) dies with display of query string and mysql_error, if query fails.

    • Example Output:

      Id      Name
      777     Aardvark
      50      Lion
      9999    Zebra
      

      提交回复
      热议问题