The accepted answer would be correct for MySQL alone, but since the question is using:
- a variable,
- appears to be using {$needle} as a replacement tag, and
- it mentions PHP
it appears the author wanted to construct the MySQL query using PHP.
Since the question was asked 12 years ago, current practice would be to use preprepared statements to prevent SQL injection.
Here is an example with 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);
Here are two resources for building PHP PDO statements: