mysql,从表单数据构建长sql查询。 (php)
我正在根据从包含搜索参数的提交表单中获取的信息编写一个大型 SQL 查询。我只是想知道是否有人对执行此操作的最佳方法有任何建议。我计划列出一个 if else 语句列表,并根据用户输入搜索表单的数据构建一个长搜索字符串。
有更好的方法吗?有什么推荐的网站或者教程吗?
谢谢。
I'm writing a large sql query based on information i'm getting from a submitted form that contains the search parameters. I'm just wondering if anyone has any recommendations on the best way of doing this. I was planning on having a list of if else statements and building a long search string based on the data the user enters search form.
Is there a better way of doing this? Any recommended sites or tutorials out there?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先,我会使用 准备好的语句 因为没有理由不这样做我从不相信用户输入。
如果您的变量位于数组或对象中,我将循环遍历它并添加变量和值(如果在 $_POST 数组中设置了变量和值)。请注意,我正在循环遍历我的数组或对象 - 不是
$_POST
- 它基本上充当白名单。您可能需要对已更改但未设置的复选框进行一些额外检查,因为它们不会出现在
$_POST
数组中。First of all I would use a prepared statement because there is no reason not to and I never trust user input.
If you have your variables in an array or an object, I would just loop through it and add the variable and value if it is set in the
$_POST
array. Note that I am looping through my array or object - not$_POST
- which basically acts as a white-list.You might need some additional checks for checkboxes that are changed and not set as they will not appear in the
$_POST
array.您仍然需要担心意外的 SQL 注入。不要跳过转义用户输入。
至于实际构建查询本身:使用 php 的控制结构来连接一系列查询部分并不少见,但很多人发现像 Zend Framework 非常方便。
You'll still need to worry about accidental SQL injection. Don't skip escaping user input.
As for actually building the query itself: It's not terribly uncommon to use php's control structures to concatenate a series of query parts, but many people find tools like the Zend Framework to be really handy.
信任但要检查。它很简单转义所有传入参数。
Trust but check. It's simple escape all incoming parameters.