[英]how to select rows where a specific string column matches at least one value inside a json array?
SELECT name FROM accounts WHERE Name in ("name1","name2");
the values are being sent inside a json array这些值在 json 数组中发送
["name1","name2"] [“名称1”,“名称2”]
currently i just convert the array into json string and remove the first and last characters目前我只是将数组转换为 json 字符串并删除第一个和最后一个字符
"name1","name2" “名称 1”、“名称 2”
but could i just keep the array intact?但我可以保持阵列完好无损吗? i tried json_contains我试过 json_contains
SELECT name FROM accounts WHERE JSON_CONTAINS(name,'["name1","name2"]');
my understanding as to which why that didn't work is because name column isn't json string array我的理解为什么这不起作用是因为名称列不是 json 字符串数组
Core issue is you can't "prepare" flex statements without some sort of preprocessing.核心问题是你不能在没有某种预处理的情况下“准备”弹性语句。
Generally you'll want to do input validation etc, on the application side regardless, and then use some sort of pre-constructor if you're not using an ORM.通常,您无论如何都希望在应用程序端进行输入验证等,然后如果您不使用 ORM,则使用某种预构造函数。
ie: IE:
$values = ["name1", "name2"];
// Validation should happen here
$inputs = substr(str_repeat("?,", count($values)), 0, -1);
$bind = str_repeat("s", count($values));
$sqli = "SELECT name FROM accounts WHERE Name in ($inputs);";
...
$stmt->bind_param($bind, ...$values);
...
You can use the same principal for PDO as well, but regaredless you're gunna want to handle the validation layer on the application side, and there is no "easy" way to inject "IN" statements into prepared SQL.您也可以对 PDO 使用相同的主体,但无论如何您都想在应用程序端处理验证层,并且没有“简单”的方法将“IN”语句注入准备好的 SQL。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.