把我的头发拉到这里试图找出问题所在,下面的代码用于过滤搜索。除非指定了位置和类别,否则所有这些都有效。除了按类别、文本和作者作品搜索之外,指定位置、文本和作者也是如此。非常感谢帮助,干杯。
来自捕获的错误消息是:异常 'PDOException' 和消息 'SQLSTATE[23000]: 完整性约束违规:D:\xampp\htdocs\eden\PET\admin\content 中的 where 子句中的列 'locationid' is ambiguous' \index.php:344 堆栈跟踪:#0 D:\xampp\htdocs\eden\PET\admin\content\index.php(344): PDOStatement->execute(Array) #1 {main}
第 344 行是: $s->execute($placeholders);
我的代码:
if (isset($_GET['action']) and $_GET['action'] == 'search')
{
include $_SERVER['DOCUMENT_ROOT'] . '/eden/PET/includes/db.inc.php';
$select = 'SELECT *';
$from = ' FROM content';
$where = ' WHERE TRUE';
$placeholders = array();
if ($_GET['author'] != '') // An author is selected
{
$where .= " AND authorid = :authorid";
$placeholders[':authorid'] = $_GET['author'];
}
if ($_GET['category'] != '') // A category is selected
{
$from .= ' INNER JOIN contentcategory ON id = contentid';
$where .= " AND categoryid = :categoryid";
$placeholders[':categoryid'] = $_GET['category'];
}
if ($_GET['locationid'] != '') // A location was selected
{
$where .= " AND locationid = :locationid";
$placeholders[':locationid'] = $_GET['locationid'];
}
if ($_GET['text'] != '') // Some search text was specified
{
$where .= " AND contenttext LIKE :contenttext";
$placeholders[':contenttext'] = '%' . $_GET['text'] . '%';
}
try
{
$sql = $select . $from . $where;
$s = $pdo->prepare($sql);
$s->execute($placeholders);
}
catch (PDOException $e)
{
$error = 'Error fetching contents!';
include 'error.html.php';
exit();
}
foreach ($s as $row)
{
$contents[] = array('id' => $row['id'], 'text' => $row['contenttext'],
'locationid' => $row['locationid']);
}
include 'contents.html.php';
exit();
}
where 子句中的列 'locationid' 不明确'
这是“有超过 1 个名为locationid
.
第二locationid
列来自contentcategory
表格,只有JOIN
在有类别时才可以使用。这就是为什么只有这种精确的过滤器组合会给您带来问题。
由于数据库无法确定locationid
您的意思,因此您需要通过更改AND locationid =
为来明确告诉它AND content.locationid =
。
正如@Wodin 在评论中所说的那样,如果您养成始终指定您所指的确切列的习惯,您将永远不会再次遇到此错误。特别是如果您需要向表中添加一列,然后不知道为什么某些看似无关的查询会突然失败。如果您觉得在每个字段之前添加content
和contentcategory
是冗长的,您可以使用表别名:
SELECT c.*
FROM content AS c
INNER JOIN contentcategory AS cc ON c.id = cc.contentid
WHERE cc.categoryid = :categoryid AND c.locationid = :locationid
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句