Php 不确定sql查询有什么问题

Php 不确定sql查询有什么问题,php,sql,Php,Sql,下面的代码是用来过滤搜索结果的,我想弄清楚到底是怎么回事。除非指定了位置和类别,否则它都可以工作。除了按类别、文本和作者进行搜索外,还可以指定位置、文本和作者。 谢谢你的帮助,干杯 catch中的错误消息是:异常“PDOException”,消息为“SQLSTATE[23000]:完整性约束冲突:1052列where子句中的“locationid”不明确,位于D:\xampp\htdocs\eden\PET\admin\content\index.php:344堆栈跟踪:0 D:\xampp\h

下面的代码是用来过滤搜索结果的,我想弄清楚到底是怎么回事。除非指定了位置和类别,否则它都可以工作。除了按类别、文本和作者进行搜索外,还可以指定位置、文本和作者。 谢谢你的帮助,干杯

catch中的错误消息是:异常“PDOException”,消息为“SQLSTATE[23000]:完整性约束冲突:1052列where子句中的“locationid”不明确,位于D:\xampp\htdocs\eden\PET\admin\content\index.php:344堆栈跟踪:0 D:\xampp\htdocs\eden\PET\admin\content\index.php344:PDOStatement->executeArray 1{main}

第344行是:$s->execute$占位符

我的代码:

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表,只有在存在类别时才能加入该表。这就是为什么只有这种过滤器的精确组合才会给您带来问题

因为数据库无法决定您指的是哪个locationid,所以需要通过将和locationid=更改为和content.locationid=来明确地告诉它

正如@Wodin在评论中所说,如果你养成习惯,总是指定你所指的确切列,你就永远不会再遇到这个错误。特别是当您需要向表中添加一列时,却不知道为什么某些看似无关的查询会突然失败。 如果您觉得在每个字段变得详细之前添加内容和内容类别,可以使用表别名:

SELECT c.*
FROM content AS c
INNER JOIN contentcategory AS cc ON c.id = cc.contentid
WHERE cc.categoryid = :categoryid AND c.locationid = :locationid

echo$sql,看看你得到了什么。结果是:从id=contentid上的内容内部联接contentcategory中选择*其中TRUE和categoryid=:categoryid和locationid=:locationidFirst,你确定要内部联接,而不是左联接吗?第二,不工作如何?我不完全确定我是否需要一个内部连接或一个左连接,我将切换到一个左连接,看看是否有任何事情发生。当您指定位置和类别时,它将捕获pdo异常;如果您指定类别、文本和作者,它将成功过滤搜索;如果您指定位置、作者和文本,它也将相应过滤搜索;如果使用左连接,它似乎不会产生任何效果,在我的情况下,工作与内心一样,非常感谢你的帮助!没问题,很乐意帮忙为了避免这种错误,您应该养成限定列名的习惯。e、 g.您应该在contentcategory.id=content.contentid等上使用内部连接contentcategory,而不是id=contentid上的内部连接contentcategory。