了解如何绑定参数并在Adodb中插入数据

时间:2010-03-02 07:45:47

标签: php sql parameters bind adodb

我被告知使用绑定参数,以便我可以将文本插入到包含引号的数据库中。但是,当涉及到如何做到这一点时,我感到非常困惑,这些命令似乎让我感到困惑。

所以,如果我有一个包含html的php字符串,我将如何使用bind参数将其插入到我的数据库中?

我想插入它,我该怎么做?

$str = '<div id="test"><a href="#">Test string in db</a></div> string content';

我被告知使用类似的东西:

$rs = $db->Execute('select * from table where val=?', array('10'));

4 个答案:

答案 0 :(得分:0)

使用 mysql_real_escape_string 也可以做到这一点,它会自动转义引号,然后您可以将数据插入数据库,请考虑以下示例:

$str = '<div id="test"><a href="#">Test string in db</a></div> string content';
$str_escaped = mysql_real_escape_string($str);

现在您可以安全地使用$str_escaped变量将数据插入数据库。此外,它还可用于防止SQL注入攻击。

答案 1 :(得分:0)

我有一段时间没有使用过ADODB,但我相信这应该可行,不是吗?

$str = '<div id="test"><a href="#">Test string in db</a></div> string content';
$rs = $db->Execute('select * from table where val=?', array($str));

答案 2 :(得分:0)

SQL中的?用作绑定到语句的值的占位符。

执行时,ADO正在执行(给出您的示例)

select * from table where val=10

您应该能够将插入SQL大致构建为:

INSERT INTO `table` (`col1`, `col2` ...) VALUES(?, ? ...)

传入您的值(按照正确的顺序)将呈现相应的查询。

答案 3 :(得分:0)

改编自CodeIgniter框架:

function compile_binds($sql, $binds)
{
    if (strpos($sql, '?') === FALSE)
    {
        return $sql;
    }

    if ( ! is_array($binds))
    {
        $binds = array($binds);
    }

    // Get the sql segments around the bind markers
    $segments = explode('?', $sql);

    // The count of bind should be 1 less then the count of segments
    // If there are more bind arguments trim it down
    if (count($binds) >= count($segments)) {
        $binds = array_slice($binds, 0, count($segments)-1);
    }

    // Construct the binded query
    $result = $segments[0];
    $i = 0;
    foreach ($binds as $bind)
    {
        $result .= mysql_real_escape_string($bind);
        $result .= $segments[++$i];
    }

    return $result;
}

然后你可以有一个功能:

function query($sql, $binds)
{
    return $db->Execute(compile_binds($sql, $binds));
}

$query = query('select * from table where val=?', array('10'));