1

我被告知使用绑定参数,以便我可以将文本插入到我的数据库中,其中包含引号。但是,当谈到如何做到这一点时,我很困惑,这些命令对我来说似乎很困惑。

那么,如果我有一个包含 html 的 php 字符串,我将如何使用绑定参数将它插入到我的数据库中?

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

$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

4 回答 4

0

Using mysql_real_escape_string should do the trick too, it escapes the quotes automatically after which you can insert data into the database, consider this example:

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

Now you can safely use the $str_escaped variable to insert data into the database. Furthermore, it is useful in preventing SQL injection attacks.

于 2010-03-02T07:50:28.700 回答
0

I haven't used ADODB for a while but I believe this should work, no?

$str = '<div id="test"><a href="#">Test string in db</a></div> string content';
$rs = $db->Execute('select * from table where val=?', array($str));
于 2010-03-02T07:50:44.860 回答
0

The ?'s in the SQL serve as placeholders for values that are bound to the statement.

When executed, ADO is executing (given your example)

select * from table where val=10

You should be able to construct your insert SQL roughly as:

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

Passing in your values (in the correct order) will render the appropriate query.

于 2010-03-02T07:56:44.473 回答
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'));
于 2010-03-02T08:56:02.940 回答