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

I am new in php and have seen many post related to this error but still can not find the problem. I also tried with the try catch block and did not get the exception. There is no connection problem and have also tested the query in my database.
$host="mysql:host=".$host_name.";dbname=".$dbname;
$ques_code=1;
$dbh = new PDO($host, $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$S=$dbh->prepare("SELECT q_code FROM question_code_submission WHERE q_num = :id");
$S->bindParam(':id', $ques_code);
$temp_name=$S->execute();
$code_name=$temp_name->fetch(PDO::FETCH_ASSOC);
$code_name=$code_name['q_code'];

$S->execute() returns true or false, so $temp_name is being set to a boolean value - which explains why you can't call $temp_name->fetch() - it's not an object.
You don't need $temp_name at all, simply:
$S->execute();
$code_name = $S->fetch(PDO::FETCH_ASSOC);

$host="mysql:host=".$host_name.";dbname=".$dbname;
$ques_code=1;
$dbh = new PDO($host, $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$S=$dbh->prepare("SELECT q_code FROM question_code_submission WHERE q_num = :id");
$S->bindParam(':id', $ques_code);
$success = $S->execute();
if(!$success){
echo "Query failed !!";
}else{
$result=$S->fetch(PDO::FETCH_ASSOC);
$code_name = $result['q_code'];
echo $code_name;
}

Related

MySQL PHP PDO remote server

I can not connect to a remote server with PDO:
public function dbConnection ($dbHost, $dbName, $dbUsername, $dbPass){
try{
$dbChain = 'mysql:host='.$dbHost.';dbname='.$dbName;
$dbh = new PDO($dbChain, $dbUsername, $dbPass);
print_r($dbh->errorInfo());
die;
...
errorInfo() only returns something if I have for instance the wrong user or password. With the right one it does not report anything, but $dbh remains empty.
errorInfo()
Array
(
[0] =>
[1] =>
[2] =>
)
$dbh
object(PDO)#5 (0) {
}
It's a remote server, but I have access using for instance MySQl Workbench, from the same machine. For the local MySQL server DB the same code works just fine.
What could be wrong with the remote connection?
Edit:
public function dbConnection ($dbHost, $dbName, $dbUsername, $dbPass){
try{
$dbChain = 'mysql:host='.$dbHost.';dbname='.$dbName;
$dbh = new PDO($dbChain, $dbUsername, $dbPass);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e){
echo $e->getMessage();
$errorCode = $e->getCode();
var_dump($errorCode);
}
I tried this and I get the same empty result.
object(PDO)#5 (0) {
}
Edit2: Same result.
$dbh = new PDO($dbChain, $dbUsername, $dbPass
, [PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
You should use a catch, after setting the proper error attributes, to see if there are errors -
try {
$dbChain = 'mysql:host='.$dbHost.';dbname='.$dbName;
$dbh = new PDO($dbChain, $dbUsername, $dbPass);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo $e->getMessage();
$errorCode = $e->getCode();
}

Errror recovering mysql data with php

i had installed freestyle extension in joomla (to allow php code in articles) im trying to access to a database in mysql with the next code
try {
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password)
$sql = "SELECT id, nombre, edad
FROM Prueba";
$q = $conn->prepare($sql);
$q->execute(array('%son'));
$q->setFetchMode(PDO::FETCH_ASSOC);
while ($r = $q->fetch()) {
echo sprintf('%s <br/>', $r['nombre']);
}
} catch (PDOException $pe) {
die("Could not connect to the database $dbname :" . $pe->getMessage());
}
?>
And i get this error in the article and i dont know why this is happening
Parse error: syntax error, unexpected T_VARIABLE on line 13
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password)
should be
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
(You're missing a ';')
Also I think your code isn't going to work exactly as planned since your SQL has no variables but you attempt to pass one to $q->execute() but I'm sure you can sort out what you're trying to do yourself...

PDO does not return error even when setting error mode

EDIT: The problem is that the errors are not being displayed. This is just to clarify everyting.
I just learned what a PDO is, and I decided to test how it works. From the tutorials I've checked, you have to use the following line to display errors: $DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
So anyways, I used this line, made sure that my query had an error and it still didn't display any errors. The connection to the database works, it always returned me an error when it couldn't connect. Anyways, here my code:
<?php
// Connection to the mysql database using PDO
$mysql_host = "hidden";
$mysql_dbname = "hidden";
$mysql_username = "hidden";
$mysql_password = "hidden";
try {
$DBH = new PDO("mysql:host=$mysql_host;dbname=$mysql_dbname", $mysql_username, $mysql_password);
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$DBH->prepare("SELECT username FROM username");
} catch (PDOException $e) {
echo "Error connecting to the database:" . $e->getMessage();
}
?>
You don't get any errors because
$DBH->prepare("DELETE use FROM blob");
doesn't execute, only prepares a query to be executed.
Replace that line of code with:
$stmt = $DBH->prepare("DELETE use FROM blob");
$stmt->execute();
You need to execute it
$stmt = $DBH->prepare("DELETE use FROM blob");
$stmt->execute();
Otherwise it doesn't actually run the query.

Call to a member function query() on a non-object on trying to read data

Hi I have been learning php from this book PHP Solutions Dynamic Web Design Made Easy and gotten to the part where I have to work with mysqli api for databases.After writing a connection function and running the script I get this error:
This is my code:
function dbConnect($usertype , $connectionType = 'mysqli'){
$host = 'localhost';
$db = 'phpsols';
if($usertype == 'read'){
$user = 'psread';
$pwd = 'Aleczandru1989';
}elseif($usertype == 'write'){
$user = 'aleczandru';
$pwd = 'Aleczandru1989';
}else{
exit('Unrecognized type');
}
if($connectionType == 'mysqli'){
return new mysqli($host , $user , $pwd , $db) or die ('Cannot open database');
}else{
try{
return new PDO("mysql:host=$host;dbname=$db", $user, $pwd);
} catch (PDOException $e){
echo 'Cannot connect to database';
exit;
}
}
}
$conn = dbConnect('read');
$sql = 'SELECT * FROM images';
$result = $conn->query($sql) or die(mysqli_error()); //Line 5
$numRows = $result->num_rows;
Line 5 in this case refers to $result = $conn->query($sql) or die(mysqli_error());.
What Am I doing wrong here?
The $conn object you are attempting to create with dbConnect('read'); fails. If you would do a var_dump($conn); it probably shows it is not what you aspect it to be. The error is actually describing what is wrong. You try to access the query function with '->query(..' on $conn. But $conn has to be an object reference that actually has the query function. The points where this object will be created are:
return new mysqli($host , $user , $pwd , $db)
and
return new PDO("mysql:host=$host;dbname=$db", $user, $pwd);
Since you are showing a different error then
or die ('Cannot open database');
My guess it is actually gong wrong at
return new PDO("mysql:host=$host;dbname=$db", $user, $pwd);
And you will catch the exception. But the echo statement is not visible anymore due to the fatal error. You will have to do some debugging there!
I have no experience with PDO, but construction of the object seems ok. (but can this help you out: http://nl1.php.net/manual/en/class.pdo.php#84751) If the construction is ok, than check if your database engine is actually running :) ?

PHP PDO Doesn't insert new records

I do not understand what my problem seem to be.
I got the following PHP code:
include_once 'db.inc.php';
try
{
$db = new PDO(DB_INFO, DB_USER, DB_PASS);
}
catch(PDOException $e)
{
echo 'Connection failed: ', $e->getMessage();
exit();
}
$title = htmlentities($_POST['title']);
$entry = htmlentities($_POST['entry']);
$sql = "INSERT INTO entries (title, entry) VALUES (?, ?)";
$stmt = $db->prepare($sql);
$stmt->execute(array($title, $entry));
$stmt->closeCursor();
I do not receive any error of any kind and the script seem to have worked however it does not insert anything into the database.
No matter what I try it doesn't do anything.
edit
Sorted :)
I didn't know about $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);.
It gave me "Uncaught exception 'PDOException' with message 'SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected'".
Turns out I wrote mysql:host=127.0.0.1;db_name=test1 instead of mysql:host=127.0.0.1;dbname=test1 in my config file.
Thank you very much for help!
Set PDO to throw exceptions when execution fails
$db = new PDO(DB_INFO, DB_USER, DB_PASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

Categories