【发布时间】:2026-02-09 05:20:06
【问题描述】:
我正在使用服务器版本 10.1.21-MariaDB 和 mysql 来执行数据操作。我正在创建用于搜索笑话的迷你搜索工具。我如何执行它的概述如图所示。一切正常,但是当我尝试执行 sql 语句时,它显示语法错误。我试图深入其中,但由于我对这些东西很陌生,所以我在这里和那里迷失了使用语法的确切方式。错误以粗体显示,下面提供了发生错误的代码。我认为错误必须在 try 块内,请帮我解决这个问题。
//query logic
$select = 'SELECT id,joketext ';
$from = 'FROM joke_info';
$where = 'WHERE TRUE';
$placeholders = array();
if(isset($_GET['author']) != ''){
$where .= " AND authorid = :authorid";
$placeholders[':authorid'] = $_GET['author'];
}
if(isset($_GET['category']) != ''){
$from .= ' INNER JOIN jokecategory ON id = jokeid';
$where .= " AND categoryid = :categoryid";
$placeholders[':categoryid'] = $_GET['category'];
}
if ($_GET['text'] != '')
{
$where .= " AND joketext LIKE :joketext";
$placeholders[':joketext'] = '%' . $_GET['text'] . '%';
}
print_r($placeholders);
try
{
$sql = $select . $from . $where;
$s = $pdo->prepare($sql);
$s->execute($placeholders);
}catch (PDOException $e)
{
$error = 'Error fetching jokes. ';
echo $error.$e->getMessage();
exit();
}
错误提示: Array ( [:authorid] => 6 [:categoryid] => 10 [:joketext] => %been working%) 获取笑话时出错。 SQLSTATE[42000]:语法错误或访问冲突:1064 您的 SQL 语法有错误;检查与您的 MariaDB 服务器版本相对应的手册,以在第 1 行的 'TRUE AND authorid = '6' AND categoryid = '10' AND joketext LIKE '%been working%'' 附近使用正确的语法
【问题讨论】:
-
打印生成的查询
-
公平地说,我不知道该怎么做。请帮帮我。错误在 try 块内,我可以肯定地说。
-
我认为您缺少 where 子句的条件。你应该有一些类似于'WHERE someValue = True and ....的东西
-
@Jens 我不行。我改了
-
@Brian 我指的是 php_mysql_novice_to_ninja,它只是说 $where ='WHERE TRUE' 仅此而已。