You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用HTML/PHP直接显示SQL数据库数据而非数组冗余内容

PHP读取SQL数据显示异常问题

正在学习PHP与SQL协同使用,尝试将SQL数据库中的数据展示在网站上。从名为subjects的表中获取id为1的subject_name字段值(预期为comment),但输出了数组相关的冗余内容,已查阅相关资源两天未解决,现有代码如下:

<?php include "head.php";
$currentPage = 'contact';
require 'db_class.php';
$db = new sql_class(); ?> 
    <header>
    <div id="banner">
        <?php include "header.php";
        
        $result = $db->execute("SELECT subject_name FROM subjects WHERE id = 1");
        // Fetch the row from the result
        $row = mysqli_fetch_assoc($result);
        
        // Store the subject name in a variable
        $subject_name = $row['subject_name'];
        ?>
    </div>
    </header>
    <body>
        <h1>Contact Us</h1>
        <form method="post">
            <input type="text" id="firstname">
            <label for="firstname">First name</label><br>
            <input type="text" id="lastname">
            <label for="lastname">Last Name</label><br>
            <input type="text" id="email" required>
            <label for="email">Email</label><br>
            <input type="text" id="phone" required>
            <label for="phone">Phone</label><br>
            <select id="subject">
                <option value="comment">Comment</option>
                <option value="doctrine">Doctrine</option>
                <option value="So"><?php echo $result;?></option>
            </select><br>
            <textarea name="" id="message" cols="30" rows="10">Your Message</textarea><br>
            <input type="submit">
        </form>
    </body>
    <?php include 'footer.php'?>
</html>

核心需求是正确显示数据库中的comment内容,目前为单个数据测试,后续将通过循环实现完整下拉菜单,以下是解决建议:

  • 修正当前显示问题:你在<option>中直接输出了MySQLi结果集对象$result,这会导致输出对象的字符串表示(冗余内容)。应该使用已经获取到的$subject_name变量替换:

    <option value="<?php echo htmlspecialchars($subject_name);?>"><?php echo htmlspecialchars($subject_name);?></option>
    
  • 增加错误处理:避免数据库查询失败或无匹配数据时出现Undefined index错误,可修改变量赋值逻辑:

    $subject_name = '';
    if ($row = mysqli_fetch_assoc($result)) {
        $subject_name = $row['subject_name'];
    }
    
  • 后续循环生成下拉菜单方案:遍历查询结果生成所有选项,同时用htmlspecialchars()转义输出内容防范XSS风险:

    <select id="subject">
        <?php
        $result = $db->execute("SELECT id, subject_name FROM subjects");
        while ($row = mysqli_fetch_assoc($result)) {
            $subject = htmlspecialchars($row['subject_name']);
            echo "<option value=\"$subject\">$subject</option>";
        }
        ?>
    </select>
    

内容的提问来源于stack exchange,提问作者Jethro Blemur

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 13:59:31