Understanding how to bind parameters and insert data in Adodb
I was told to use bind parameters so that I could insert text into my db that had quotes in it. But, I am pretty confused when it comes to how to do this, the commands seem confusing to me.
So, if I had a php string, that contained html, how would I insert this into my DB using bind parameters?
I wanted to INSERT it, how would I do this?
$str = '<div id="test"><a href="#">Test string in db</a></div> string content';
I was told to use something like:
$rs = $db->Execute('select * from table where val=?', ar开发者_运维百科ray('10'));
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));
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.
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.
Adapted from the CodeIgniter framework:
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;
}
Then you could have a function:
function query($sql, $binds)
{
return $db->Execute(compile_binds($sql, $binds));
}
$query = query('select * from table where val=?', array('10'));
精彩评论