SQL查询未显示所有列数据

时间:2018-01-29 15:00:04

标签: php mysql

我遇到了php代码的问题。我试图从sql数据库获取所有数据,但它没有向我显示费用列。它显示来自所有其他列的所有其他数据。

<?php
$mysqli = new mysqli("localhost", "root", "", "stu_data");

/* check connection */
if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}

$query = "SELECT id, degree, fee FROM degree";

if ($result = $mysqli->query($query)) {

    /* fetch associative array */
    while ($row = $result->fetch_assoc()) {
      printf ("%s (%s)\n", $row["id"], $row["degree"], $row["fee"]);
    }

    /* free result set */
    $result->free();
}

/* close connection */
$mysqli->close();
?>

3 个答案:

答案 0 :(得分:1)

while ($row = $result->fetch_assoc()) {
      echo  "ID: ".$row["id"]." DEGREE: ".$row["degree"]." FEE: ".$row["fee"];
    }

你有两个$ s的printf,正如第一条评论所述。使用echo而不是printf。

答案 1 :(得分:1)

while ($row = $result->fetch_assoc()) {
    printf ("%s (%s)\n", $row["id"], $row["degree"], $row["fee"]);
}

应该是:

while ($row = $result->fetch_assoc()) {
    printf ("%s (%s, %s)\n", $row["id"], $row["degree"], $row["fee"]);
}

你有2%s有3个变量,所以你忘记了一个。

已更新以在表格中查看:

<?php
    $mysqli = new mysqli("localhost", "root", "", "stu_data");

    /* check connection */
    if ($mysqli->connect_errno) {
        printf("Connect failed: %s\n", $mysqli->connect_error);
        exit();
    }

    $query = "SELECT id, degree, fee FROM degree";

    if ($result = $mysqli->query($query)) {

        /* fetch associative array */
        echo "<table>";
        echo "<tr><th>ID</th><th>Degree</th><th>Fee</th></tr>";
        while ($row = $result->fetch_assoc()) {
            printf ("<tr><td>%s</td><td>%s</td><td>%s</td></tr>", $row["id"], $row["degree"], $row["fee"]);
        }
        echo "</table>";

        /* free result set */
        $result->free();
    }

    /* close connection */
    $mysqli->close();
?>

答案 2 :(得分:0)

您在printf功能中缺少第三种格式参数。尝试再添加一个%s参数

<?php
$mysqli = new mysqli("localhost", "root", "", "stu_data");

/* check connection */
if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}

$query = "SELECT id, degree, fee FROM degree";

if ($result = $mysqli->query($query)) {

    /* fetch associative array */
    while ($row = $result->fetch_assoc()) {
      printf ("ID:%s, degree:(%s), fee:%s\n", $row["id"], $row["degree"], $row["fee"]);
    }

    /* free result set */
    $result->free();
}

/* close connection */
$mysqli->close();
?>