Call to a member function setFetchMode() error - php

I've been getting this error,
"Fatal error: Call to a member function setFetchMode() on a non-object in C:\Users\Public\wamp\www\audiotextCSVUpload\modified.php on line 34".
Can you please help me what is causing the error. In one of my computer, it is ok, but in our office, the error exists. Find below the code:
<?php
require_once 'dbconfig.php';
try {
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$sql = 'SELECT phone, last_name, first_names
FROM contacts';
$q = $conn->query($sql);
$q->setFetchMode(PDO::FETCH_ASSOC);
} catch (PDOException $pe) {
die("Could not connect to the database $dbname :" . $pe->getMessage());
}
?>

check for error
$q = $conn->query($sql);
if (!$q) {
echo "\nPDO::errorInfo():\n";
print_r($conn->errorInfo());
}

It seems the problem is with your query, table contacts do not exists or the fields you are retrieving aren't correct.
It's a good idea to add exceptions to PDO, add this after $conn
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
And check for the error

Related

IS NOT NULL giving null values

I have the following PHP code using PDO. I want rows with empty values to not appear in the results. How do I achieve this, and what am I doing wrong below?
<?php
require_once 'dbconfig.php';
try {
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
echo "Connected to $dbname at $host successfully.";
$sql = 'SELECT *
FROM as_questions
WHERE Answer IS NOT NULL';
$q = $conn->query($sql);
$q->setFetchMode(PDO::FETCH_ASSOC);
} catch (PDOException $pe) {
die("Could not connect to the database $dbname :" . $pe->getMessage());
}
As above suggested by two persons (Fred -ii and Alex Anderi) please change your query like below:-
$sql = "SELECT * FROM as_questions WHERE Answer !=''";

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

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.

php pdo statement error

I'm a newbie to php pdo. Here i'm trying to fetch my database records from database using prepared statements. But it didn't fetch the records. I'm getting this following error
Fatal error: Uncaught exception 'PDOException' with message
'SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected
why i'm getting this error? why it didn't fetch the records from database?
<?php
$user = "root";
$password = "password";
try {
$conn = new PDO('mysql:host=localhost;database=evouchers', $user, $password);
$conn -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
echo 'DATABASE ERROR : ' . $e->getMessage();
}
$sql = "SELECT UserName FROM ebusers ORDER BY UserName";
$db = $conn->query($sql);
$db->setFetchMode(PDO::FETCH_ASSOC);
while($row = $db->fetch())
{
print_r($row);
}
?>
in your db connection string instead of database use dbname
$conn = new PDO('mysql:host=localhost;database=evouchers', $user, $password);
---------------------------------------^
$conn = new PDO('mysql:host=localhost;dbname=evouchers', $user, $password);
Docs link: http://php.net/manual/en/pdo.connections.php
I think it should be
$conn = new PDO('mysql:host=localhost;dbname=evouchers', $user, $password);
Alternatively try just after you init PDO
$conn->exec('USE evouchers;');
use the following line for pdo connection
$conn = new PDO('mysql:host=localhost;dbname=evouchers', $user, $password);

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);

Error with a prepared statement with named placeholders in PHP with mySQL

I am getting these errors on my webpage with this code
Notice: Undefined variable: dbh in /home/danu2_cj3/public_html/lists.php on line 14
Fatal error: Call to a member function prepare() on a non-object in /home/danu2_cj3/public_html/lists.php on line 14
This is the php code i am using and line 14 is the 4th line in this code
<?php
/* Execute a prepared statement by binding PHP variables */
$member = $_SESSION['SESS_MEMBER_ID'];
$sth = $dbh->prepare('SELECT name
FROM lists
WHERE member_id = :member_id ');
$sth->bindValue(':member_id', $member, PDO::PARAM_INT);
$sth->execute();
?>
I am trying to show an array of a bunch of rows where one of the fields in those rows is supposed to match the member_id for the person logged into the session
here is the whole code for the page (top.php and bottom.php are just layout pages)
<?php include ('top.php')?>
<h1>My Profile </h1>
My Lists | Logout</br>
</br>
Please select list to view/delete
<?php include ("connect.php")?>
<?php
/* Execute a prepared statement by binding PHP variables */
$member = $_SESSION['SESS_MEMBER_ID'];
$sth = $dbh->prepare('SELECT name
FROM lists
WHERE member_id = :member_id ');
$sth->bindValue(':member_id', $member, PDO::PARAM_INT);
$sth->execute();
?>
<?php include ('bottom.php')?>
Here is my connect.php file
<?php
$username = "mydb";
$password = "mydb";
$hostname = "host";
//connection to the database
$dbh = mysql_connect($hostname, $username, $password)
or die("Unable to connect to database");
//select a database to work with
$selected = mysql_select_db("mydb",$dbh)
or die("Could not select database");
?>
You should probably add connection to database or check if it is correctly set in connect.php
try
{
$dbh = new PDO($dsn, $user, $password);
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
DOCUMENTATION HERE

Categories