我一直在试图弄清楚如何用MySQL进行查询,检查某个列中的值(字符串$haystack)是否包含某些数据(字符串$needle),就像这样:

SELECT *
FROM `table`
WHERE `column`.contains('{$needle}')

在PHP中,这个函数被称为substr($haystack, $needle),所以可能:

WHERE substr(`column`, '{$needle}')=1

当前回答

请注意,这是危险的:

WHERE `column` LIKE '%{$needle}%'

第一:

$needle = mysql_real_escape_string($needle);

这样可以防止可能的攻击。

其他回答

WHERE `column` LIKE '%$needle%'

请注意,这是危险的:

WHERE `column` LIKE '%{$needle}%'

第一:

$needle = mysql_real_escape_string($needle);

这样可以防止可能的攻击。

接受的答案将是正确的MySQL单独,但由于问题是使用:

一个变量, 似乎正在使用{$needle}作为替换标记,并且 它提到了PHP

似乎作者想用PHP构造MySQL查询。

由于这个问题是12年前提出的,目前的实践是使用预准备语句来防止SQL注入。

下面是一个PHP的例子:

function check_connection ($user, $pass, $db = 'test', $host = '127.0.0.1', $charset = 'utf8mb4') {
     if (isset($GLOBALS['conn']) && is_object($GLOBALS['conn']) && ($GLOBALS['conn'] instanceof PDO)) {
          if (same_database($db) === true) {
               $connection = &$GLOBALS['conn']; 
          }
          else {
               $GLOBALS['conn'] = pdo_connect($user, $pass, $db, $host, $charset);
               $connection = &$GLOBALS['conn'];       
          }
     }
     else {
          $GLOBALS['conn'] = pdo_connect($user, $pass, $db, $host, $charset);
          $connection = &$GLOBALS['conn'];
     }

     return $connection;
}

function pdo_connect ($user, $pass, $db, $host, $charset){    
     $dsn = "mysql:host=$host;dbname=$db;charset=$charset";
     $options = [
       PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
       PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
     ];
     try {
       return new PDO($dsn, $user, $pass, $options);
     } 
     catch (\PDOException $e) {
       throw new \PDOException($e->getMessage(), (int)$e->getCode());
     }
}

function same_database($db) {
    if (isset($GLOBALS['conn']) && is_object($GLOBALS['conn']) && ($GLOBALS['conn'] instanceof PDO)) {
        $sql = "SELECT DATABASE() AS 'database'";
        $sth = $GLOBALS['conn']->prepare($sql);
        $sth->execute();
        if (strcasecmp(trim($sth->fetchAll(PDO::FETCH_ASSOC)['0']['database']), trim($db)) === 0) { 
            return true;
        }
    }

    return false;
}
    
$conn = check_connection($user, $pass, $db, $host, $charset);

$sql = "
     SELECT *
     FROM `table`
     WHERE `column` like :needle
";

// Concatenating the % wildcard before and after our search variable
$bind = array(
     ':needle' => '%'.$needle.'%'
);

$sth = $conn->prepare($sql);
$sth->execute($bind);

// Being redundant about fetch_assoc incase it was not set in pdo() options
$result = $sth->fetchAll(PDO::FETCH_ASSOC);

// You would use rowCount(), instead of fetchAll(), if it is NOT a SELECT statement
// $sth->rowCount();

print_r($result);

下面是构建PHP PDO语句的两个资源:

PHP妄想PDO教程 PHP手册PDO

其实很简单:

SELECT *
FROM `table`
WHERE `column` LIKE '%{$needle}%'

%是任意字符集的通配符(无、一个或多个)。请注意,这可能会在非常大的数据集上变慢,所以如果你的数据库增长,你就需要使用全文索引。

Use:

SELECT *
  FROM `table`
 WHERE INSTR(`column`, '{$needle}') > 0

参考:

INSTR