0

我目前正在为上传系统创建一个数据库 - 我正在使用一个选择框来限制添加到数据库中的类别数量。

<select name="category">
<?php
$conn = mysqli_connect("localhost", "blah", "blah") or die ("No connection");

mysqli_select_db($conn, "UPLOAD") or die("db will not open");

$query = "SELECT category FROM details GROUP BY category";

$result = mysqli_query($conn, $query) or die("Invalid query");

while($row = mysqli_fetch_array($result)) {
                echo "<option value=\"" . $row[0] . "\">" . $row[0] . "</option>";
                }               
             mysqli_close($conn);
            ?>
     </select>

    <select name="reaction">
            <?php
            $conn = mysqli_connect("localhost", "blah", "blah") or die ("No connection");

            mysqli_select_db($conn, "UPLOAD") or die("db will not open");

            $query = "SELECT reaction FROM details GROUP BY reaction";

            $result = mysqli_query($conn, $query) or die("Invalid query");

            while($row = mysqli_fetch_array($result)) {
                echo "<option value=\"" . $row[0] . "\">" . $row[0] . "</option>";
                }               
             mysqli_close($conn);
            ?>

虽然这两个查询是相同的 - 只有类别(顶部查询)停止从我的数据库中重复多个数据。当我查看我的数据库时 - 这就是我所发现的(我有预感可能是问题所在)。

INSERT INTO `details` (`name`, `category`, `reaction`, `photo`, `date_added`) VALUES
('Mase Laughing', 'Funny', 'Laugh\n', 'mase-laugh.gif', '2013-05-01 07:16:26'),
('Movie Wink', 'Cheeky', 'Wink\n', 'movie-wink.gif', '2013-05-02 12:33:12'),
('Tarzan Giggle', 'Funny', 'Wink\r\n', 'tarzan-laugh.gif', '2013-05-02 01:33:00');

除了反应之外,我还收到了这些奇怪的\r\n信件——有人有什么想法吗?提前致谢。

4

2 回答 2

0

这些是“回车”(\r)和“换行”(\n)字符。这些命令告诉您的计算机走到行尾并换行。

要阻止您的页面显示重复的类别,请更改以下内容:

$query = "SELECT category FROM details GROUP BY category";

进入这个:

$query = "SELECT distinct category FROM details GROUP BY category";

它不会阻止您的数据库存储重复的类别(您不希望这样做,否则您将只能为每个类别保存 1(一)行详细信息,但它会阻止您的下拉列表(选择)显示重复项。所以, 使用您显示的详细信息,它将为您提供一个下拉列表,其中包含值 'Funny' 和 'Cheecky',它们都只显示一次。也将“distinct”添加到您的其他 SQL 语句中,以消除重复的反应:

$query = "SELECT DISTINCT reaction FROM details GROUP BY reaction"; 
于 2013-05-02T11:47:02.857 回答
0

在这里,我通过减少冗余代码来更新原始问题

<?php
    $conn = mysqli_connect("localhost", "root", "") or die ("No connection");
    mysqli_select_db($conn, "test") or die("db will not open");
?>
<select name="category">
<?php

    $query = "SELECT category FROM details GROUP BY category";
    $result = mysqli_query($conn, $query) or die("Invalid query");
    while($row = mysqli_fetch_array($result)) {
        echo "<option value='" . $row[0] . "'>" . $row[0] . "</option>";
    }               
?>
</select>

<select name="reaction">
<?php
    $query = "SELECT reaction FROM details GROUP BY reaction";
    $result = mysqli_query($conn, $query) or die("Invalid query");

    while($row = mysqli_fetch_array($result)) {
        echo "<option value='" . $row[0] . "'>" . $row[0] . "</option>";
    }               
    mysqli_close($conn);
?>
</select>
于 2013-05-02T12:52:37.057 回答