我目前正在为上传系统创建一个数据库 - 我使用一个选择框来限制添加到数据库的类别数。
<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
字母的反应之外 -
有人有主意吗?
提前谢谢。
答案 0 :(得分: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";
答案 1 :(得分: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>