我的字段曾经工作正常,但是当我切换连接到数据库的配置文件以使用 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);
}
}
白猪掌柜的