douchu2823 2009-07-01 06:15
浏览 20
已采纳

用于在MySQL Query中转义不同变量类型的函数

I got sick of writing queries in my PHP as:

"WHERE '" . Database::escape($var) . "'";

The escape() function just calls mysql_real_escape_string() - but it's there so I can extend support to other databases later.

Having to single quote strings in the query was making my code more cluttered. So my idea was to create an other function in my database class to 'prepare' a variable for a query:

static public function prepare($var)
{

    if (is_object($var) || is_array($var) ) {
        return " '" . Database::escape(serialize($var)) . "' ";

    } else if (is_bool($var)) {
        return ' ' . (int)$var . ' ';

    } else if (is_int($var)) {
        return ' ' . $var . ' ';

    } else if (is_string($var) || is_float($var)) {
        return " '" . Database::escape($var) . "' ";

    } else {
        throw new Exception('Unsupported variable type [' . gettype($var) . ']');
    }
}

Now the benefit here is that, I don't need to worry about which variables I pass to a query. However it raises two questions:

  1. Am I handling each variable type properly?
  2. For what reason (if any) should I not do this?
  • 写回答

4条回答 默认 最新

  • dongshuiga2826 2009-07-01 06:26
    关注

    You are looking for a) pepared statements and b) a database abstraction layer (like PDO).

    What you are trying to do on your own has been solved already, you should not roll your own implementation.

    If you go down that road you'll notice that this:

    "... WHERE '" . Database::escape($var) . "'"
    

    is pointless and dangerous. A clear separation of SQL code and parameters requires you to be more explicit and gets you on the safe side against SQL injection the same time:

    "--- WHERE SomeField = ?"  /* the parameter (?) will be filled elsewhere */
    

    It's worth noting that true vendor-independence in the database field is somewhere between hard and impossible, depending on your needs and priorities. So trying to write portable SQL could turn out as an exercise in futility unless you are willing to sacrifice a lot. For MySQL it starts even with the LIMIT clause, which you will find impossible to port to, say, SQL Server.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题