我想让它使网址显示用户所在页面的cat_name。目前它是 category.php?id=2 或
category.php?id=' . $row['cat_id'] . '
我想让它成为类别.php?标题=足球或
category.php?title=' . $row['cat_name'] . '
但是,当我替换该行时,它会导致另一页上出现问题。
页面类别.php为:
<?php
//category.php
include 'connect.php';
//first select the category based on $_GET['cat_id']
$sql = "SELECT
cat_name,
cat_id,
cat_description
FROM
categories
WHERE
cat_id = '" . mysql_real_escape_string($_GET['id']) ."'";
$result = mysql_query($sql);
if(!$result)
{
echo 'The category could not be displayed, please try again later.' . mysql_error();
}
else
{
if(mysql_num_rows($result) == 0)
{
echo 'This category does not exist.';
}
else
{
//display category data
while($row = mysql_fetch_assoc($result))
{
echo '<h2>Topics in ′' . $row['cat_name'] . '′ category</h2><br />';
}
//do a query for the topics
$sql = "SELECT topic_id, topic_subject, topic_date, topic_cat
FROM topics
JOIN categories
ON topics.topic_cat = categories.cat_id
WHERE cat_id = " . mysql_real_escape_string($_GET['id']);
$result = mysql_query($sql);
if(!$result)
{
echo 'The topics could not be displayed, please try again later.';
}
else
{
if(mysql_num_rows($result) == 0)
{
echo 'There are no topics in this category yet.';
}
else
{
//prepare the table
echo '<table border="1">
<tr>
<th>Topic</th>
<th>Created at</th>
</tr>';
while($row = mysql_fetch_assoc($result))
{
echo '<tr>';
echo '<td class="leftpart">';
echo '<h3><a href="topic.php?id=' . $row['topic_id'] . '">' . $row['topic_subject'] . '</a><br /><h3>';
echo '</td>';
echo '<td class="rightpart">';
echo date('d-m-Y', strtotime($row['topic_date']));
echo '</td>';
echo '</tr>';
}
}
}
}
}
?>
问题是,当我替换 url 时,它会使第二个$sql(下面那个:对主题进行查询)不起作用。我想让它使 sql 与对 url 的更改一起工作。
我想将cat_id更改为cat_name,但是当我这样做时,它会出现它不起作用的错误。所以问题是 sql 需要 GET 与cat_id在一起,而我希望 url 具有cat_name。我在 sql 查询中更改了什么才能使用该cat_name并使其正常工作?
希望这是对问题的更好解释。告诉我您是否需要更多信息谢谢莱恩
JOIN
语法似乎是你想要的。
一般来说,它像
SELECT <fields>
FROM table1
JOIN table2
ON table1.key = table2.key
WHERE <conditions>
ON
告诉数据库应该使用哪些键来"匹配"行。 <table>.<field>
语法允许您指定字段来自哪个表,以防表包含相同的字段名称。
因此,您可以将查询调整为类似
$sql = "SELECT topic_id, topic_subject, topic_date, topic_cat
FROM topics
JOIN categories
ON topics.topic_cat = categories.cat_id
WHERE cat_name = " . mysql_real_escape_string($_GET['title']);
你可以
试试INNER JOIN
:
SELECT
t.topic_id, t.topic_subject, t.topic_date, t.topic_cat, c.cat_id, c.cat_name
FROM
topics as t
INNER JOIN
categories as c
WHERE
topic_cat = ". mysql_real_escape_string($_GET['title']) ."
AND
t.topic_cat = c.cat_id
这个怎么样,
$sql = "SELECT
topic_id,
topic_subject,
topic_date,
topic_cat
FROM
topics
JOIN
other_table
ON
topics.topic_cat = other_table.id
AND
other_table.title = '" . mysql_real_escape_string($_GET['title'])."'";
这样做的原因是,它将从联接的topic_cat表中选择上述四个字段,并使用两个表的外键进行other_table。从中,它将选择数据,其中 other_table.title = $_GET['title']。