通过JSON从MySQL和PDO中自动完成字段



我的字段过去工作得很好,但当我将连接到数据库的配置文件切换为使用PDO时,它停止了工作。我更新了php文件如下,但数据仍然不会填充。

下面是我的配置文件和PHP文件,该文件提取数据并通过AJAX将其以JSON形式发送回我的页面。这是我第一次与PDO合作。

配置文件:

class DatabaseService{
private $db_host = "localhost";
private $db_name = "ca_us_data";
private $db_user = "root";
private $db_password = "";
private $connection;
public function getConnection(){
$this->connection = null;
try{
$this->connection = new PDO("mysql:host=" . $this->db_host . ";dbname=" . $this->db_name, 
$this->db_user, $this->db_password);
}catch(PDOException $exception){
echo "Connection failed: " . $exception->getMessage();
}
return $this->connection;
}
}
?>

提取文件:

$databaseService = new DatabaseService();
$conn = $databaseService->getConnection();
if(!isset($_POST['selected_country'])){
$keyword = strval($_POST['query']);
$search_param = "%{$keyword}%";
$stmt = $conn->prepare("SELECT country_name FROM 'countries' WHERE country_name LIKE ?");
$stmt->bindParam(':search_param', $search_param, PDO::PARAM_STR);
$stmt->execute();
$num = $stmt->rowCount();
if($num > 0){
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$countryResult[] = $row["country_name"];
}
echo json_encode($countryResult);
}
}

我认为您的查询中没有':search_param',请用:search_param替换?,然后重试:

$stmt = $conn->prepare("SELECT country_name FROM countries WHERE country_name LIKE :search_param");
$stmt->bindParam(':search_param', $search_param, PDO::PARAM_STR);

最新更新