简体   繁体   中英

Using SQL LIKE with variable PHP

I can't use the SQL LIKE with a variable

$sql = "SELECT * FROM chat WHERE name LIKE 'Motherboard' "; //This works

But if a use a variable it doesn't work:

$sql = "SELECT * FROM chat WHERE name LIKE '%'+$variable+'%' ";
//or
$sql = "SELECT * FROM chat WHERE name LIKE '$variable' ";

How can I fix it?

在PHP中,您使用点将字符串连接起来。

 $sql = "SELECT * FROM chat WHERE name LIKE '" . $variable . "' ";

You also can use variables within double quotes:

$sql = "SELECT * FROM chat WHERE name LIKE '$variable' ";

or

$sql = "SELECT * FROM chat WHERE name LIKE '{$variable}' ";

Keep in mind that double quotes work slower then single. In your case it would be

$sql = "SELECT * FROM chat WHERE name LIKE '%{$variable}%' ";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM