PDO - "Call to a member function fetch() on a non-object" - php

I know that error occurs usually when query returned false but this time this occurs with no reason! (or just I'm making a big mistake)
if(!$security_SenderId){
$getbaseticketqry = $this->db->prepare("SELECT * FROM `tickets` WHERE `ticket_safeid` = '?'");
$getbaseticket = $getbaseticketqry->execute(array($ticket_safeid));
}else{
$getbaseticketqry = $this->db->prepare("SELECT * FROM `tickets` WHERE `ticket_safeid` = '?' AND `ticket_sender` = '?'");
$getbaseticket = $getbaseticketqry->execute(array($ticket_safeid, $security_SenderId));
}
if($getbaseticket === false){
return false;
}else{
$baseticket = $getbaseticket->fetch(PDO::FETCH_ASSOC);
}
I've theese lines in a function that returns support ticket information as array but as I said the error occurs when I tried to fetch the ticket information. I tried to check mysql errors just before fetch line by enabling the pdo debug mode and db->errorInfo() but it didn't work.
What can the problem be here?
Edit:
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
class TICKET_MANAGER
{
function __construct($dbhost, $dbname, $dbuser, $dbpass) {
try{
$this->db = new PDO("mysql:host=$dbhost;dbname=$dbname;charset=utf8", $dbuser, $dbpass);
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
die('Connection failed: ' . $e->getMessage() );
}
}
function viewTicket($ticket_safeid, $security_SenderId = false)
{
try{
if(!$security_SenderId){
$getbaseticketqry = $this->db->prepare("SELECT * FROM `tickets` WHERE `ticket_safeid` = ?");
$getbaseticket = $getbaseticketqry->execute(array($ticket_safeid));
}else{
$getbaseticketqry = $this->db->prepare("SELECT * FROM `tickets` WHERE `ticket_safeid` = ? AND `ticket_sender` = ?");
$getbaseticket = $getbaseticketqry->execute(array($ticket_safeid, $security_SenderId));
}
}catch(PDOException $e){
die('Mysql error: ' . $e->getMessage() );
}
...
}
...
}

It's the quotes around all your '?' - Remove them.
Read the manual
http://php.net/pdo.prepared-statements
from the manual:
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)");
Exceptions should have told you that error
setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION)
and used right after you've connected to your DB.
-http://php.net/manual/en/pdo.error-handling.php
try {
$dbh = new PDO($dsn, $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
Query:
try {
// your query
}
catch(PDOException $e){
print $e->getMessage();
}
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.

Related

How to fetch data from a MS-SQL Server Database using PHP?

I'm trying to fetch data from a SQL Server database. After debugging, I could figure there's something wrong with the function.
Here's the code:
db.php
class Db{
public static function getConnection() {
$server='xxx';
$database='xxx';
$user='xxx';
$password='xxx';
$dsn="dblib:host=" . $server . ";dbname=" . $database;
try {
$conn = new PDO($dsn, $user, $password);
}
catch (PDOException $e) {
echo 'SQL SERVER CONNECTION ERROR: ' . $e->getMessage();
}
return $conn;
}
}
functions.php
class Functions {
function getAcademicYear() {
$db = new Db();
$conn = $db->getConnection();
$conn->beginTransaction();
$sql = "SELECT academicYear FROM AcademicYear ORDER BY academicYearId DESC LIMIT 5";
$stmt = $conn->prepare($sql);
if ($stmt->execute()) {
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$conn->commit();
echo $result;
} else {
$conn->rollback();
echo "false";
}
}
}
The function is returning false. Can you please review it and point out any mistakes?

PHP executes sql inside a false condition of IF statement with $_POST

Please help with this difficult to understand bug: php always execute sql update inside IF with $_POST in condition.
When condition is false: the code i) not executes the echo command, but ii) it still executes the sql command
if ($_POST["scanned_set"] != "saved") {
try {
$conn = new PDO("mysql:host=$servername;dbname=abc", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
// Update
$sql = "UPDATE `id_scan` SET `scan_count` = 10 WHERE `id_scan`.`id` = 1";
// use exec() because no results are returned
$conn->exec($sql);
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
$conn = null;
}
and the strange thing is that, if I try the iF condition with "IF (1 ==2)" then code works well. In other words, it does not execute the sql.
The full code
<html>
<body>
<?php
$servername = "localhost";
$username = "reviinve_vchain";
$password = "";
var_dump($_POST["scanned_set"]);
try {
$conn = new PDO("mysql:host=$servername;dbname=reviinve_vchain", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
// Retrieve data from db
$sql = "SELECT * FROM `id_scan` WHERE `id` = 1";
foreach ($conn->query($sql) as $row) {
echo "print scan number after retrieving statement ".$row['scan_count'] . "\t";
// print $row['color'] . "\t";
$count_update = $row['scan_count'] + 1;
}
}
catch(PDOException $e){
echo "Connection failed: " . $e->getMessage();
}
$conn = null;
if ($_POST["scanned_set"] != "saved") {
try {
$conn = new PDO("mysql:host=$servername;dbname=reviinve_vchain", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
// Update count number to db
echo 'new count number' . $count_update;
$sql = "UPDATE `id_scan` SET `scan_count` = $count_update WHERE `id_scan`.`id` = 1";
// use exec() because no results are returned
$conn->exec($sql);
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
$conn = null;
}
?>
</body>
</html>
Try scrubbing your request variable first:
$do_update = !(trim(strtolower($_REQUEST["scanned_set"])) == "saved")
if ($do_update) {
try {
$conn = new PDO("mysql:host=$servername;dbname=abc", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
// Update
$sql = "UPDATE `id_scan` SET `scan_count` = 10 WHERE `id_scan`.`id` = 1";
// use exec() because no results are returned
$conn->exec($sql);
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
$conn = null;
}

Query dont work

I just transfered my website to another hosting, but some scripts stop working, many very simple as this:
mysql_query("INSERT INTO orders (userid,cid,tipou,cantidad,factura,producto,lote,notas,cprod,pbase,cenvio,fecha,status,cobro,ip)
VALUES ('{$_SESSION['id_usuario']}','{$cid}','{$tipou}','{$cantidad}','{$factura}','{$producto}','{$numlot}','{$notas}','{$cprod}','{$pbase}','{$cenvio}','{$fecha}','{$status}','{$cobro}','{$ip}')");
Im using php version 5.6, And tryed to enable Error Reporting, but I dont got any warnings, the query don't INSERT any data on the table.
Please apologize my english, and thanks for helping.
This is how i set it up pretty much:
connect.php:
<?php
define('DB_HOSTNAME', 'HOSTNAME');
define('DB_USERNAME', 'USERNAME');
define('DB_PASSWORD', 'PASSWORD');
define('DB_DATABASE', 'DATABASE');
function dataQuery($query, $params) {
$queryType = explode(' ', $query);
// establish database connection
try {
$dbh = new PDO('mysql:host='.DB_HOSTNAME.';dbname='.DB_DATABASE, DB_USERNAME, DB_PASSWORD);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo $e->getMessage();
$errorCode = $e->getCode();
}
// run query
try {
$queryResults = $dbh->prepare($query);
$queryResults->execute($params);
if($queryResults != null && 'SELECT' == $queryType[0]) {
$results = $queryResults->fetchAll(PDO::FETCH_ASSOC);
return $results;
}
$queryResults = null; // first of the two steps to properly close
$dbh = null; // second step to close the connection
}
catch(PDOException $e) {
$errorMsg = $e->getMessage();
echo $errorMsg;
}
}
?>
Then i just use functions to do the work:
<?php
function functionNameHere() {
$query = "INSERT INTO orders (userid,cid,tipou,cantidad,factura,producto,lote,notas,cprod,pbase,cenvio,fecha,status,cobro,ip) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
$params = array($_SESSION['id_usuario'],etc...);
dataQuery($query,$params);
}
?>
then just call <?php functionNameHere(); ?>
Created this:
$sessid = $_SESSION['id_usuario'];
if (!$mysqli->query("INSERT INTO orders (userid,cid,tipou,cantidad,factura,producto,lote,notas,cprod,pbase,cenvio,fecha,status,cobro,ip)
VALUES ('".$sessid."','".$cid."','".$tipou."','".$cantidad."','".$factura."','".$producto."','".$numlot."','".$notas."','".$cprod."','".$pbase."','".$cenvio."','".$fecha."','".$status."','".$cobro."','".$ip."')")) {
echo "Falló la Insersión de Datos: (" . $mysqli->errno . ") " . $mysqli->error;
} else {echo"Datos Insertados";}
Working on localhost, but not in my server.

Want to delete a row from a table using php pdo

I want to delete a row from a table using php pdo.I am using the following code,
$dsn = 'mysql:host=127.0.0.1;dbname=as1';
$user = 'root';
$password = '';
try {
// Connect and create the PDO object
$pdo = new PDO($dsn, $user, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo 'Database connection failed - ';
echo $e->getMessage();
exit;
}
$sql1="DELETE FROM photo WHERE id=?";
$q1=array($result);
try {
$stmt1 = $pdo->prepare($sql1);
$stmt1->execute($q1);
$stmt1->setFetchMode(PDO::FETCH_BOTH);
$result1= $stmt1->fetchColumn();
}
catch (PDOException $e) {
die("Failed to run query: " . $e->getMessage());
}
But my datas in a table are not deleting ...It shows failed to run query..
You did not provide a value for ?
$stmt1->execute($q); // Where is $q defined?
Should be something like
$q=array(1);
$stmt1->execute($q);

Invalid Data Source PHP PDO Mysql

<?php
#require_once('inc/dbc1.php');
$dsn = 'mysql:dbname=dbname;host=somehost;
$user = 'someuser';
$password = 'SomePass';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$pdo1 = new PDO($dsn, $user, $password);
$pdo1->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sth1 = $pdo1->prepare('SELECT pID, lname, fname FROM Professor ORDER BY pID DESC LIMIT 5;');
$sth1->execute(array());
?>
Throws the error:
Uncaught exception 'PDOException' with message 'invalid data source name' in PDO->__construct('', NULL, NULL) on line 1
Anyone see anything wrong with this?
you have
$dsn = 'mysql:dbname=dbname;host=somehost;
maybe just maybe ...
$dsn = 'mysql:dbname=dbname;host=somehost';
unless this was a mouso when cut-and-pasting the question.

Categories