gpt4 book ai didi

php - 建立数据库连接 PDO 时出错

转载 作者:行者123 更新时间:2023-11-29 08:12:57 25 4
gpt4 key购买 nike

我正在使用 PDO 连接到 MySQL

include_once('connection_insert.php');
global $host, $dbname, $user, $pass;
$DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$DBH->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION); ///*** for error handling

function insert_terms(){
global $DBH;
$STH = $DBH->prepare("INSERT IGNORE INTO table
(name,state)
value (?,?)");
return $STH;
$DBH = Null;// Closing Connection
}

但是我遇到错误:

Error establishing a database connection

我的问题是,这是使用 global $DBH; 和关闭连接 $DBH = Null;//Closing Connection

的正确方法吗?

编辑

connection_insert.php

$host = 'localhost';
$user = 'username';
$pass = 'password';
$dbname = 'db';

最佳答案

不,使用全局变量是不好的做法(不要看Wordpress和其他人使用全局变量)。结构(架构)应用程序越复杂 - 使用全局变量的后果可能就越可怕。你可以找到很多关于为什么它们是邪恶的信息。相反,你可以使用模式 Registry (例如)用于访问应用程序中的“全局”变量。简而言之,有很多选择。

关于您的代码。连接参数($host,$dbname,$user,$pass)定义了吗?

另请参阅Global or Singleton for database connection?php.net .

编辑示例:

索引.php

require_once 'Database.php';

$DB = new Dababase();
$DB->prepare("INSERT IGNORE INTO table (name,state) value (:name,:state)");
$database->bind(':name', 'NAME');
$database->bind(':state', 'STATE');
$DB->execute();

配置.php

define("DB_HOST", "localhost");
define("DB_USER", "username");
define("DB_PASS", "password");
define("DB_NAME", "database");

数据库.php

require_once 'config.php'; 

class Database{
private $host = DB_HOST;
private $user = DB_USER;
private $pass = DB_PASS;
private $dbname = DB_NAME;

private $dbh;
private $error;
private $stmt;

public function __construct(){
// Set DSN
$dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
// Set options
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
// Create a new PDO instanace
try{
$this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
}
// Catch any errors
catch(PDOException $e){
$this->error = $e->getMessage();
}
}

public function prepare($query){
$this->stmt = $this->dbh->prepare($query);
}

public function query($query){
return $this->dbh->query($query);
}

public function bind($param, $value, $type = null){
if (is_null($type)) {
switch (true) {
case is_int($value):
$type = PDO::PARAM_INT;
break;
case is_bool($value):
$type = PDO::PARAM_BOOL;
break;
case is_null($value):
$type = PDO::PARAM_NULL;
break;
default:
$type = PDO::PARAM_STR;
}
}
$this->stmt->bindValue($param, $value, $type);
}

public function execute(){
return $this->stmt->execute();
}

public function execute(){
return $this->stmt->execute();
}

public function fetchRows(){
$this->execute();
return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
}

public function fetchRow(){
$this->execute();
return $this->stmt->fetch(PDO::FETCH_ASSOC);
}

}

关于php - 建立数据库连接 PDO 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21207179/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com