PDO query breaks after php upgrade from 7 to 8
by Robert S from LinuxQuestions.org on (#5Q9DN)
I have just upgraded from php 7.4 to 8.0. I have a file called functions.php which is called by a number of scripts, which sets up a PDO object:
Code:<?php
class PDO_database
{
var $sth;
var $db;
function PDO_database( $dsn, $username, $password )
{
$this->db = new PDO( $dsn, $username, $password );
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $this->db;
}
function query( $query )
{
try
{
$this->sth = $this->db->query( $query );
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
exit;
}
return $this->sth;
}
}
?>I call this from another script - index.php
Code:<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
include( 'functions.php' );
$dbh = new PDO_database('mysql:host=localhost;dbname=SOME_DATABASE;charset=utf8', 'SOME_TABLE', 'XXX_SOME_PASSWORD_XXX');
$query = 'SELECT * FROM `SOME_TABLE` ORDER BY `Date`;';
$sth = $dbh->query( $query );
?>
</body>
</html>When I call the query method, I get an error:
Quote:
Can somebody please explain what's happening, and what the solution is? This worked with php7.4.
Code:<?php
class PDO_database
{
var $sth;
var $db;
function PDO_database( $dsn, $username, $password )
{
$this->db = new PDO( $dsn, $username, $password );
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $this->db;
}
function query( $query )
{
try
{
$this->sth = $this->db->query( $query );
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
exit;
}
return $this->sth;
}
}
?>I call this from another script - index.php
Code:<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
include( 'functions.php' );
$dbh = new PDO_database('mysql:host=localhost;dbname=SOME_DATABASE;charset=utf8', 'SOME_TABLE', 'XXX_SOME_PASSWORD_XXX');
$query = 'SELECT * FROM `SOME_TABLE` ORDER BY `Date`;';
$sth = $dbh->query( $query );
?>
</body>
</html>When I call the query method, I get an error:
Quote:
PHP Fatal error: Uncaught Error: Call to a member function query() on null in functions.php:17\nStack trace:\n#0 index.php(11): PDO_database->query()\n#1 {main}\n thrown in functions.php on line 17 |