Ayan Ayan - 4 months ago 40
SQL Question

PDO execute not found error given in PHP storm

I have a file named chat.php with a namespace MyApp and am trying to connect to database using PDO and insert some data but in my IDE I get an error saying Method execute not found. Where am I going wrong?

Following are some parts of the code:

<?php

namespace MyApp;

use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use Emojione\Client;
use Emojione\Ruleset;
use \PDO;
use \PDOException;

class Chat implements MessageComponentInterface {
protected $clients;
/**
* @var \Emojione\Client
*/
private $emojioneClient;

public function __construct() {
$this->clients = new \SplObjectStorage;
/**
* Following for setting up conversion and display of native and ascii emojis
*/
$this->emojioneClient = new Client(new Ruleset());
$this->emojioneClient->imageType = 'png';
$this->emojioneClient->imagePathPNG = './assets/png/';
$this->emojioneClient->ascii = true;

$this->connect();
}
.
.
.
.
.

public function connect() {
$hostname='localhost';
$dbname = 'cryptoIM';
$username='root';
$password='';

try {
$dbh = new PDO("mysql:host=$hostname; dbname=$dbname", $username, $password);

$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo 'Connected to Database<br/>';
}
catch(PDOException $e)
{
echo ('ERROR: ' . $e->getMessage());
}
}

public function insertData() {
$query = $dbh->prepare("INSERT INTO inbox(users, message, attachmentURI, timestamps) VALUES (:username, :messagetxt, :attachmentURI, :unixtime)");
$query->execute(array(
"username" => "",
"messagetxt" => "",
"attachmentURI" => "",
"unixtime" => ""
));
}

Answer

Apparently, $dbh is not available in insertData() scope. Try to add $dbh to $this (class scope), and you must add colons : to your execute() array keys.

class Chat implements MessageComponentInterface {
    protected $clients;
    protected $dbh;

then:

public function connect() {
    //...    
    try {
        $this->dbh = new PDO("mysql:host=$hostname; dbname=$dbname", $username, $password);

        $this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        echo 'Connected to Database<br/>';
    }
    catch(PDOException $e)
    {
        echo ('ERROR: ' . $e->getMessage());
    }
}

then:

public function insertData() {
    $query = $this->dbh->prepare("INSERT INTO inbox(users, message, attachmentURI, timestamps) VALUES (:username, :messagetxt, :attachmentURI, :unixtime)");
    $query->execute(array(
        ":username" => "", //Don't forget to add colons ':'
        ":messagetxt" => "",
        ":attachmentURI" => "",
        ":unixtime" => ""
    ));
}

About the error Method execute not found. I think you must get Call to a member function on a non-object or something similar !