php - 在 PHP 中搜索 MySQL 中的 JSON 数据

标签 php mysql json search

上次我发布了有关搜索的问题 JSON data using PHP 。测试脚本后我想尝试其他东西。使用MySQL 来搜索数据。因为它比使用 PHP 脚本循环所有内容更快。 我正在 PhpMyAdmin 中编写脚本,它为我生成了下一个 PHP 脚本。但某个地方有一个错误(悲伤)

"SELECT * 
 FROM `bigtree_pages` 
 WHERE `resources` like \'%\"XNCatDesc\": \"%?%\' and `resources` like \'%\"Brand\": \"%?%\' and `resources` like \'%\"ItemDesc\": \"%?%\'"

我想给出三个值。类别、品牌和 ItemDesc(名称)。但这会引发错误。

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '\'%"XNCatDesc": "%'41'%\' and resources like \'%"Brand": "%'none'%\' and `reso'

说实话,我真的不知道我必须把%符号放在哪里。 例如。我的 JSON "Brand": "Bullet", 中有这个 该值必须是 Brand (因为我们正在搜索 Brand),并且品牌是 Bullet。编写此查询的最佳方式是什么?

最佳答案

要在准备好的查询中的 LIKE 表达式中使用参数,您需要形成整个表达式并将其用作参数。否则,您会遇到在值中插入引号时遇到的问题。如果您使用的是 mysqli,请尝试类似的操作(假设您的连接名为 $conn 并且您要搜索的值名为 $categorie >、$brand$itemdesc):

$stmt = $conn->prepare("SELECT * 
                        FROM `bigtree_pages` 
                        WHERE `resources` like ? and `resources` like ? and `resources` like ?");
$search_categorie = "%\"XNCatDesc\": \"%$categorie%\"";
$search_brand = "%\"Brand\": \"%$brand%\"";
$search_itemdesc = "%\"ItemDesc\": \"%$itemdesc%\"";
$stmt->bind_param("sss", $search_categorie, $search_brand, $search_itemdesc);
$stmt->execute();

但是,您将遇到的问题是,由于查询中的搜索值周围有 %(例如 $brand),因此在搜索 brand 时= X 例如,您可以匹配

"Brand": "Y", "Other Value": "contains an X"

因此,您应该使用正则表达式,例如

$stmt = $conn->prepare("SELECT * 
                        FROM `bigtree_pages` 
                        WHERE `resources` rlike ? AND `resources` rlike ? AND `resources` rlike ?");
$search_categorie = '"XNCatDesc":[[:space:]]+"[^"]*' . $categorie;
$search_brand = '"Brand":[[:space:]]+"[^"]*' . $brand;
$search_itemdesc = '"ItemDesc":[[:space:]]+"[^"]*' . $itemdesc;
$stmt->bind_param("sss", $search_categorie, $search_brand, $search_itemdesc);
$stmt->execute();

如果您运行的是 MySQL 5.7 或更高版本,最好使用内置 JSON_EXTRACT 来完成此操作。功能:

$stmt = $conn->prepare("SELECT * 
                        FROM `bigtree_pages` 
                        WHERE JSON_EXTRACT(`resources`, '$.XNCatDesc') LIKE ? and
                              JSON_EXTRACT(`resources`, '$.Brand') LIKE ? and 
                              JSON_EXTRACT(`resources`, '$.ItemDesc') LIKE ?");
$search_categorie = "%$categorie%";
$search_brand = "%$brand%";
$search_itemdesc = "%$itemdesc%";
$stmt->bind_param("sss", $search_categorie, $search_brand, $search_itemdesc);
$stmt->execute();

关于php - 在 PHP 中搜索 MySQL 中的 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53980945/

相关文章:

php - 从 Android Studio 的 Mysql 数据库获取数据

php - HTML。表单成功完成后如何停止重定向?

mysql - SQL 测量两天之间的差异

javascript - json 对象与对象数组

android - Android 中的 JSON 解析问题

php - 用户得分的 SQL 排名,从任意位置

php - 如何修改 zii.widgets.CBreadcrumbs 自动生成的 html?

php - 从 CodeIgniter Active Record 类调用存储过程

javascript - TinyMCE返回html标签

mysql - 为什么 ActiveRecord 生成的 SQL 包含时间列的日期?