在PHP中显示sql表中的所有数据?

时间:2015-02-01 02:32:22

标签: php mysql

当我打印我的代码时,它只打印id = 1的问题和描述,但不打印表的其余部分。

这是我的代码。

请告诉我如何打印我的整个表格,大概有20个左右的问题......还请告诉我如何制作它以便问题留在浏览器上(即使我刷新页面)因为目前刷新页面时,数据不会保留在浏览器上。

非常感谢!

<?php

require_once "connection.php";

if(isset($_POST['submit'])) {

    $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME );

    if($conn->connect_error) {

        die("connection error: " . $conn->connect_error);
    } else {

        echo "Submit button connected to database!";
    }

    $question = $_POST['question'];
    $description = $_POST['description'];

    $sql = " INSERT INTO `ask` (question_id, question, description) VALUES
    (NULL, '{$question}', '{$description}' ) ";

    if($conn->query($sql)) {

        echo "it worked";
    } else {

        echo "error: " . $conn->error;

        exit();
    }


    $query = "SELECT * FROM `ask` ";

    if( $result = $conn->query($query)) {
        $fetch = $result->fetch_assoc();

        echo "<p>{$fetch['question']}</p>";
        echo "<p>{$fetch['description']}</p>";

    } else {
        echo "failed to fetch array";
    }






}


?>

2 个答案:

答案 0 :(得分:0)

每个循环都需要一个:

    <?php

require_once "connection.php";

if(isset($_POST['submit'])) {

    $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME );

    if($conn->connect_error) {

        die("connection error: " . $conn->connect_error);
    } else {

        echo "Submit button connected to database!";
    }

    $question = $_POST['question'];
    $description = $_POST['description'];

    $sql = " INSERT INTO `ask` (question_id, question, description) VALUES
    (NULL, '{$question}', '{$description}' ) ";

    if($conn->query($sql)) {

        echo "it worked";
    } else {

        echo "error: " . $conn->error;

        exit();
    }


    $query = "SELECT * FROM `ask` ";

    if( $result = $conn->query($query)) {
        $fetch = mysql_fetch_array($result, MYSQL_ASSOC);
        foreach($fetch as $ques) {
            echo "<p>" . $ques['question'] . "</p>";
            echo "<p>" . $ques['description'] . "</p>";
        }

    } else {
        echo "failed to fetch array";
    }






}


?>

我所做的就是改变:

$fetch = $result->fetch_assoc();

echo "<p>{$fetch['question']}</p>";
echo "<p>{$fetch['description']}</p>";

为:

$fetch = mysql_fetch_array($result, MYSQL_ASSOC);
foreach($fetch as $ques) {
    echo "<p>" . $ques['question'] . "</p>";
    echo "<p>" . $ques['description'] . "</p>";
}

答案 1 :(得分:0)

fetch_assoc() - 将结果行作为关联数组

所以它只需要一行,你需要遍历其余行检查示例reference from php docs