【发布时间】:2023-03-03 05:15:21
【问题描述】:
我最近开始复兴一个旧的 PHP4.# 网站。在这样做的过程中,我一直试图弄清楚到 PDO 的转换。在对 PDO 结构进行了这么多不同的尝试之后,我迷路了,我的代码越来越疯狂。我认为问题在于我没有正确实例化 pdo 类,但使用几种不同的方法都失败了。
致命错误:未捕获错误:调用 /home/folder/database/insert.php:36 中未定义的方法 DBInsert::__construct()
mysqlhelper.php
<?php
class MySQLHelper
{
private $link;
private $db;
private $user;
private $pass;
var $pdo;
public function __construct()
{
$host = 'localhost';
$db = 'dbname';
$user = 'username';
$pass = 'supersecret';
$port = '1111';
$options = [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
\PDO::ATTR_EMULATE_PREPARES => false,
];
try {
$dsn = "mysql:host=$host;dbname=$db;port=$port";
$this->pdo = new PDO($dsn, $user, $pass, $options);
return $this->pdo;
} catch (\PDOException $e) {
throw new \PDOException($e->getMessage(), (int)$e->getCode());
echo "Connection failed";
}
}
function __destruct()
{
// Closing connection
$this->pdo = null;
}
public function query($query)
{
// Performing SQL query
$result = $this->pdo->query($query) or die('Query failed: ' . mysql_error());
return $result;
}
插入.php
<?php
include "../helpers/mysqlhelper.php";
class DBInsert
{
private $helper;
private $nations;
private $nations_updated;
private $stagedslots;
private $stagednations_new; // nations that need to be inserted
private $stagednations_old; // nations that need to be updated
var $pdo;
//this function was previously called __construct() prior to my 11/22/20 updates
function somethingelse()
{
$this->helper = new MySQLHelper();
$this->stagedslots = array();
$this->nations_updated = array();
$this->nations = array();
$q = "SELECT * FROM `nations`";
$result = $this->helper->query($q);
$result = $this->helper->getResultArray($result);
foreach ($result as $val)
{
$this->nations[$val["id"]] = $val;
}
}
public function clearSlots()
{
$sql = "DELETE FROM `slots`;";
$object = new MySQLHelper;
$object->__construct();
line 36 $stmt = $this->__construct()->prepare($sql);
$stmt->execute();
}
对于第 36 行,我也尝试过 $stmt = $this->pdo->prepare($sql);这也会产生错误。
感谢任何建议。
【问题讨论】:
-
"//这个函数以前叫__contruct()" 是叫
__contruct()还是__construct()? -
不确定
var $pdo;在 PHP 中是否有效 -
@kerbh0lz 有效,但不推荐。
-
@Martin 感谢您的信息
-
var $pdo在这种情况下正在做public $pdo的工作,这就是它通常的写法。
标签: php pdo instantiation