php 中搜索词包含特殊字符时出错
Error when search words contain special characters in php
我在搜索带有特殊字符的术语时遇到致命的 PHP 错误(示例 John O'Malley
)。 Mysql 数据库字符集是 utf8_unicode_ci
dbconn.php 文件
<?php
$DB_host = "removed";
$DB_user = "removed";
$DB_pass = "removed";
$DB_name = "removed";
try
{
$DBcon = new PDO("mysql:host={$DB_host};dbname={$DB_name};charset=utf8",$DB_user,$DB_pass);
$DBcon->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "";
}
php 页
<?php
$stmt = $DBcon->prepare("SELECT * FROM player WHERE player_name LIKE '%$Search%' LIMIT 25");
$stmt->execute();
?>
我收到错误消息
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'Malley%' LIMIT 25' at line 1' in /../results.php:167 Stack trace: #0 /../results.php(167): PDOStatement->execute() #1 {main} thrown in /../results.php on line 167
你已经完成了一半。准备好的语句将允许您执行此查询,但您必须正确使用它们。要正确使用它们,您必须参数化查询。所有值都应该是查询中的占位符,然后它们应该被绑定。
尝试:
$stmt = $DBcon->prepare("SELECT * FROM player WHERE player_name LIKE concat('%', ?, '%') LIMIT 25");
$stmt->execute(array($Search));
我在搜索带有特殊字符的术语时遇到致命的 PHP 错误(示例 John O'Malley
)。 Mysql 数据库字符集是 utf8_unicode_ci
dbconn.php 文件
<?php
$DB_host = "removed";
$DB_user = "removed";
$DB_pass = "removed";
$DB_name = "removed";
try
{
$DBcon = new PDO("mysql:host={$DB_host};dbname={$DB_name};charset=utf8",$DB_user,$DB_pass);
$DBcon->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "";
}
php 页
<?php
$stmt = $DBcon->prepare("SELECT * FROM player WHERE player_name LIKE '%$Search%' LIMIT 25");
$stmt->execute();
?>
我收到错误消息
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'Malley%' LIMIT 25' at line 1' in /../results.php:167 Stack trace: #0 /../results.php(167): PDOStatement->execute() #1 {main} thrown in /../results.php on line 167
你已经完成了一半。准备好的语句将允许您执行此查询,但您必须正确使用它们。要正确使用它们,您必须参数化查询。所有值都应该是查询中的占位符,然后它们应该被绑定。
尝试:
$stmt = $DBcon->prepare("SELECT * FROM player WHERE player_name LIKE concat('%', ?, '%') LIMIT 25");
$stmt->execute(array($Search));