Using the code below, I get the error, “Call to undefined method stdClass::fetchObject()”.
function getProdDetails2SaveInInvoice($data) {
global $dbh;
try {
$sth=$dbh->prepare("
SELECT
AES_DECRYPT('alt_id', ?),
AES_DECRYPT('prod_name', ?),
AES_DECRYPT('prod_desc', ?)
FROM
products
WHERE
prod_id = ?
");
$sth->execute($data);
$rs = $sth->query(PDO::FETCH_ASSOC);
return $rs;
}
catch(PDOException $e) {
echo "Something went wrong. Please report this error.\n";
file_put_contents(
$_SERVER['DOCUMENT_ROOT']."/PDOErrors.txt",
"\n\nScript name : ".SCRIPT."\nFunction name : ".__FUNCTION__."\n".
$e->getMessage(), FILE_APPEND);
throw new failedTransaction();
}
}
$data = array(
DBKEY, /* field 1 */
DBKEY, /* field 2 */
DBKEY, /* field 3 */
$prodid /* comparison */
);
$rs = getProdDetails2SaveInInvoice($data);
while ($row = $rs->fetchObject()) {
echo $row->prod_name;
}
Unfortunately, this doesn’t work and returns the error mentioned above.
I can confirm that the $dbh database connection is working as it’s the same connection working for the inserts and updates. Thanks.
UPDATE
This is how I’ve amended my code based on the suggestions below, but I’m still getting nothing returned:
try {
$dbh = new PDO("mysql:host=".CO_DB_HOST.";dbname=".CO_DB_NAME, CO_DB_UNAME, CO_DB_PWORD);
$dbh ->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch(PDOException $e) {
echo $e->getMessage();
}
function getProdDetails2SaveInInvoice($data) {
global $dbh;
try {
$sth=$dbh->prepare("
SELECT
AES_DECRYPT('alt_id', ?),
AES_DECRYPT('prod_name', ?),
AES_DECRYPT('prod_desc', ?)
FROM
products
WHERE
prod_id = ?
");
$sth->execute($data);
while ($row = $sth->fetchObject()) {
// PROCESS ROW
$rs = array($row->alt_id, $row->prod_name, $row->prod_desc);
}
return $rs;
}
catch(PDOException $e) {
echo "Something went wrong. Please report this error.\n";
file_put_contents(
$_SERVER['DOCUMENT_ROOT']."/PDOErrors.txt",
"\n\nScript name : ".SCRIPT."\nFunction name : ".__FUNCTION__."\n".
$e->getMessage(), FILE_APPEND);
throw new failedTransaction();
}
}
// Fetch additional info from invoice_products.
$data = array(
DBKEY, /* field 1 */
DBKEY, /* field 2 */
DBKEY, /* field 3 */
$prodid /* comparison */
);
$rs = getProdDetails2SaveInInvoice($data);
print_r($rs);
If I hardcode the ‘where’ argument (19), it still does not retrieve the result. Ideally I think I should retrieve the result in an object so that it can be streamed, but right now, I’d be happy even if it came in a box!
The data is definitely existing in the database and can be pulled using a traditional query.
This is the output of the print_r($rs):
Array
(
[0] =>
[1] =>
[2] =>
)
You should loop over the prepared statement, and not call
queryon the prepared statement. Basic usage of prepared statements is as follows:As an alternative you could also use
$sth->fetchAll()which returns an array with all rows that are the result of your query, see PDOStatement::fetchAll().