duanpu5048 2014-01-25 14:02
浏览 17
已采纳

MySQL插入前检查[关闭]

A more general question about MySQL. I was wondering how much of checks can/should I do directly at SQL level. For example, I'm building a forum where admins can post stickies. Currently, when posting a message, PHP checks the session of the user to see if that user is an admin. My question is: would there be a way to make an INSERT query that only insert the new topic as a sticky (stick = true) if user_is_admin under the user_id of the user currently attempting to post the message is true? Would it be possible/desirable to do that?

  • 写回答

1条回答 默认 最新

  • douqiao6015 2014-01-25 15:36
    关注

    To answer part 1 of your question (is it possible?), yes, it is possible.

    MySQL has an IF function which can be used within INSERT and UPDATE statements to set the value of column depending on other factors within the scope of the statement.

    The syntax is IF(expr,if_true_expr,if_false_expr), so it works a bit like the ternary operator in PHP, C, Java, etc. See http://www.mysqltutorial.org/mysql-if-function.aspx.

    As for whether it is desirable, that ulitmately depends on the overall context, but in general using vendor-specific SQL makes your application less portable. Furthermore the logic gets split between the PHP and the SQL so may be less easy to understand and refactor, changes to the DB structure make break the SQL code, you are less likely to realise the benefits of using MVC frameworks which handle the SQL layer for you, etc, so not desirable.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 wpf界面一直接收PLC给过来的信号,导致UI界面操作起来会卡顿
  • ¥15 init i2c:2 freq:100000[MAIXPY]: find ov2640[MAIXPY]: find ov sensor是main文件哪里有问题吗
  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒