mgr*_*aph 11 php mysql wordpress wpdb
我有这个:
$villes = '"paris","fes","rabat"';
$sql = 'SELECT distinct telecopie FROM `comptage_fax` WHERE `ville` IN(%s)';
$query = $wpdb->prepare($sql, $villes);
Run Code Online (Sandbox Code Playgroud)
我做的时候echo $query;得到:
SELECT distinct telecopie FROM `comptage_fax` WHERE `ville` IN('\"CHAPELLE VIVIERS \",\"LE MANS \",\"QUEND\"')
Run Code Online (Sandbox Code Playgroud)
在probleme我已经是$wpdb加'在IN('...')
有人可以帮忙,谢谢
Dav*_*dom 36
试试这段代码(修复):
// Create an array of the values to use in the list
$villes = array("paris", "fes", "rabat");
// Generate the SQL statement.
// The number of %s items is based on the length of the $villes array
$sql = "
SELECT DISTINCT telecopie
FROM `comptage_fax`
WHERE `ville` IN(".implode(', ', array_fill(0, count($villes), '%s')).")
";
// Call $wpdb->prepare passing the values of the array as separate arguments
$query = call_user_func_array(array($wpdb, 'prepare'), array_merge(array($sql), $villes));
echo $query;
Run Code Online (Sandbox Code Playgroud)
Tur*_*çam 14
WordPress已经有了一个用于此目的的函数,请参阅esc_sql().以下是此函数的定义:
转义用于MySQL查询的数据.通常你应该使用wpdb :: prepare()来准备查询.有时,斑点逃逸是必需的或有用的.一个例子是准备一个用于IN子句的数组.
你可以像这样使用它:
$villes = ["paris", "fes", "rabat"];
$villes = array_map(function($v) {
return "'" . esc_sql($v) . "'";
}, $villes);
$villes = implode(',', $villes);
$query = "SELECT distinct telecopie FROM `comptage_fax` WHERE `ville` IN (" . $villes . ")"
Run Code Online (Sandbox Code Playgroud)
小智 6
功能:
function escape_array($arr){
global $wpdb;
$escaped = array();
foreach($arr as $k => $v){
if(is_numeric($v))
$escaped[] = $wpdb->prepare('%d', $v);
else
$escaped[] = $wpdb->prepare('%s', $v);
}
return implode(',', $escaped);
}
Run Code Online (Sandbox Code Playgroud)
用法:
$arr = array('foo', 'bar', 1, 2, 'foo"bar', "bar'foo");
$query = "SELECT values
FROM table
WHERE column NOT IN (" . escape_array($arr) . ")";
echo $query;
Run Code Online (Sandbox Code Playgroud)
结果:
SELECT values
FROM table
WHERE column NOT IN ('foo','bar',1,2,'foo\"bar','bar\'foo')
Run Code Online (Sandbox Code Playgroud)
可能有效率,也可能没有效率,但是它是可重用的。