示例PDO
/* Assume $pdo is already prepared as PDO instance. */
// search query split by spaces
$user_input = 'foo bar baz';
// create string for PDO::prepare()
$sql = 'SELECT * FROM testTable WHERE ';
$wheres = $values = array();
foreach (array_filter(explode(' ', $user_input), 'strlen') as $keyword) {
$wheres[] = 'col1 LIKE ?';
$values[] = '%' . addcslashes($keyword, '%_\\') . '%'; // this is escape for LIKE search
}
$sql .= $wheres ? implode(' OR ', $wheres) : '1';
// bind values and execute
$stmt = $pdo->prepare($sql);
$stmt->execute($values);
示例mysql_**
功能(廢棄)
/* Assume $link is already prepared as MySQL resource. */
// search query split by spaces
$user_input = 'foo bar baz';
// create string for mysql_auery()
$sql = 'SELECT * FROM testTable WHERE ';
foreach (array_filter(explode(' ', $user_input), 'strlen') as $keyword) {
$wheres[] = 'col1 LIKE ' . mysql_real_escape_string(
'%' . addcslashes($keyword, '%_\\') . '%',
$link
);
}
$sql .= !empty($wheres) ? implode(' OR ', $wheres) : '1';
// execute
$result = mysql_query($sql, $link);
您最好在'PDO'上使用**準備好的語句**。您當前的代碼允許** SQL注入**攻擊。 – mpyw
如果我使用mysql_real_esacep_string(),它會保護它嗎? – user1477731
是的,但'mysql _ **'函數**已棄用**。看到這裏http://www.php.net/manual/en/function.mysql-real-escape-string.php你可以選擇'Mysqli'或'PDO'。我建議你'PDO'。 – mpyw