Mvrk Mvrk - 5 months ago 57
MySQL Question

PDO could not be converted to string php

Learning PHP OOP way:

Pass database class object to other class i got this message ' Catchable fatal error: Object of class PDO could not be converted to string ' , meanwhile the code work fine if I comment this line '

//$imageobj= new image($dbobj);
' ?

Update : once I add this line
function in db.class.php before try{} . every thing WORKS fine !!!


include "./classes/db.class.php";
include "./classes/image.class.php";

$dbobj= new db();
$imageobj= new image($dbobj);

$page_title="Shopping Center !";
include './template/header.php';


include './template/footer.php';


class db {
private $host;
private $dbname;
private $username;
private $password;
private $dbconn;
private $status;

public function __construct() {
// the require paramaters to start db connnection
$this->host = '';
$this->dbname = 'shop_carta';
$this->username = 'root';
$this->password = '';
$this->status = 0;
//$this->dbconn = null;

public function getConnection() {
try {
$this->dbconn = new PDO("mysql:host=$this->host;dbname=$this->dbconn", $this->username, $this->password);
if (!is_null($this->dbconn)) {

$this->status = $this->dbconn->getAttribute(PDO::ATTR_CONNECTION_STATUS);
$this->dbconn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$this->dbconn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

return $this->dbconn;
} else {
echo "<div class='alert alert-danger'>"
. " Our server Busy Now try again later.. </div></br>";
return false;
} catch (PDOException $ex) {
return false;

this class receive the $dbobject try to $dbobject->getConncetion() and set retrieve

class image {
private $table_name = 'product_images';
private $dbconn;
public $id;
public $name;

public function __construct($dbobj) {
$this->dbconn = $dbobj->getConnection();

Error message once you pass $dbobj to image class

once you commit line $imageobj= new image($dbobj); in index.php

Assign dbconn to null solve :
Catchable fatal error: Object of class PDO could not be converted to string.
Any suggestion WHY ?

enter image description here

Answer Source

The issue lies here:


dbname should be a database name. You are providing a property, which (before you added $this->dbconn = null) does not exist, which is why you get an error.

Adding $this->dbconn = null, does prevents the fatal on the non existant property, but youre still providing an empty database name.

You should fix it by replacing it with $this->dbname, like so:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download