重用Sprintf参数或PHP中的替代方法

时间:2014-05-14 14:37:02

标签: php mysql arguments printf

我有一个很长的UNION,下面只是查询的一小部分:

UNION 
(
    /* Get new contact requests to you */
        SELECT r.registered, r.id, u.x_account_username, r.message AS comment, '' AS name, 'new_contact_request' AS type
            FROM x_allies r
            LEFT JOIN x_user u
            ON r.from = u.id
            WHERE r.registered BETWEEN '%s' AND '%s' AND r.to = '%s'
)

我一直在使用 sprintf 函数将正确的值插入到我的查询中。

但是,我遇到了一个问题。

我的sprintf现在看起来像这样..

如何在sprintf函数中重用参数?

$query      =   sprintf($query, $c, $t, $c, $a, $c, $e, $profile_id, $profile_id, $profile_id, $tryblimp, $now, $profile_id, $c, $tryblimp, $now, $profile_id, $c, $tryblimp, $now, $profile_id, $c, $tryblimp);

I have seen implementations of re-using arguments within PHP, but I can't seem to get it working. Here is what I have found already.

你能帮我找一个解决方案吗?

由于

1 个答案:

答案 0 :(得分:0)

将值直接插入SQL查询字符串是非常糟糕的做法,因为您应该非常小心参数引用。否则,这可能会导致SQL注入或SQL错误。 我建议您使用PDO语句和parameters,如下所示:

$query = 'Select * FROM table WHERE registered BETWEEN :begin AND :end';
$parametersValues = array(':begin' => $bedigDate, ':end' => $endDate);
$statement = $db->prepare($query);
$statement->execute($parametersValues);
$result = $statement->fetchAll();