Fatal Error: fetch() - php

I have the below snippet of code. When I run the whole program, it fails at this section with the error Fatal error: Call to a member function fetch() on a non-object in <filename> on line 26. I'm really not sure what I should do to fix the problem. If it matters, I ran the SQL query against my database and it returns exactly what it should.
if(isset($_POST['submit'])) {
$query = 'SELECT email FROM users WHERE email=:email';
$query_params = array(':email' => $_POST['email']);
try {
$stmt = $conn->prepare($query);
$result = $stmt->execute($query_params);
} catch(PDOException $ex) {
echo $ex->getMessage();
}
$row = $result->fetch(); //fails on this line
if(empty($results)) {
$passset = 1;
}
}

PDOStatement::execute returns TRUE or FALSE, not a result object.
Change this:
$row = $result->fetch();
To this:
$row = $stmt->fetch();

Related

mysqli array fetching is not getting data

I have to fetch result in single row but I can't run multiple rows. How can I fix this?
$stmt = $this->conn->prepare("SELECT * from user where id=?");
$stmt->bind_param("s", $id);
if($stmt->execute()){
$result = $stmt->get_result()->fetch_array(MYSQLI_ASSOC);
$stmt->close();
return $result;
}
I Got Result Like Wise This
{"ID":2,"Name":"Anju"}
But i need to get all user result .my code is here
$stmt = $this->conn->prepare("SELECT * from user where id=?");
$stmt->bind_param("s", $id);
if($stmt->execute()){
$result = array();
while ($row = $stmt->get_result()->fetch_array(MYSQLI_ASSOC)) {
$result[] = $row;
}
$stmt->close();
return $result;
}
I got the error
Fatal error: Call to a member function fetch_array() on a non-object in line 5
The line is:
while ($row = $stmt->get_result()->fetch_array(MYSQLI_ASSOC))
my expecting result is
{"ID":1,"Name":"Obi"}, {"ID":3,"Name":"Oman"}, {"ID":4,"Name":"Anju"}
$stmt = $this->conn->prepare("SELECT * from user where id=?");
$stmt->bindValue(1, $id);
Try that way
And try to fetchAll instead of fetch_array
You could make following correction.
Change
$rows->fetch_assoc(MYSQLI_ASSOC)
to
$rows->fetch_assoc()
It should look like
if ($stmt->execute()) {
$rows = $stmt->get_result();
$result = array();
while ($row = $rows->fetch_assoc()){
$result[] = $row;
}
$stmt->close();
return $result;
} else {
return NULL;
}
Suggestion : Always specify the list of columns in your SELECT, which makes query execution faster.
Please read php manual

Cannot execute prepared statement "Fatal error: Call to a member function prepare() on null" error

So I have this code
$lang=new language();
$default_language=$lang->getLanguage(0);
$currencies = new currency();
$currencies = $currencies->getCurrencies();
getCurrencies() and getLanguage() are in another file with classes.
public function getCurrencies() {
$curr=new record();
return $curr -> getRecords('currencyTable','currency_order',array("currency_id","currency_name"));
}
public function getLanguage($record) {
$lang=new record();
return $lang->getRecord('languageTable',$record,'lang_order','*');
}
And getRecords and getRecord are public functions it the record class
I keep on getting the error
Fatal error: Call to a member function prepare() on null
Referring to the query of the getRecords functions.
I dont know how to fix this. Does this has to do with the connection to the database?
Also, the weird part is that if I remove the
$lang=new language();
$default_language=$lang->getLanguage(0);
part, this error goes away. Any help? Is the error in the $default_language=$lang->getLanguage(0); line and this is why it is messing up the database connection, resulting to this error?
Thanks
EDIT
Here are the getRecord and getRecords
public function getRecords($table,$sorder,$field_names) {
$conn = db::open();
//- build string of field names
if($field_names!='*'){
$field_string="";
foreach ($field_names as $value) {
$field_string.=",".$value;
}
$field_string = substr($field_string,1);
}else{
$field_string='*';
}
//end up with field1, field2... or *
//soreder is a field, contains int like 1 2 3
//- run statement
$stmt = $conn->prepare("SELECT ".$field_string." FROM ".$table." ORDER BY ".$sorder." ASC");
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $results;
}
and
public function getRecord($table,$record,$sorder,$field_names) {
$conn = db::open();
if($field_names!='*'){
$field_string="";
foreach ($field_names as $value) {
$field_string.=",".$value;
}
$field_string = substr($field_string,1);
}else{
$field_string='*';
}
//same things for $field_string and $sorder
$stmt = $conn->prepare("SELECT ".$field_string." FROM ".$table." ORDER BY ".$sorder." LIMIT ? OFFSET ?");
$stmt->bindValue(1, 1 , PDO::PARAM_INT);
$stmt->bindValue(2, $record, PDO::PARAM_INT);
$stmt->execute();
$results = $stmt->fetch(PDO::FETCH_ASSOC);
return $results;
}
I fixed an error. In getRecord I had LIMIT 1 and I fixed it as above. I still get the same error about the getRecords line : $stmt = $conn->prepare("SELECT ".$field_string." FROM ".$table." ORDER BY ".$sorder." ASC");
Any thoughts?
Thanks
Your database connection failed. The error is not in your posted code. The error in your code is when the statement is being prepared.
Ex: $statement = $dbh->prepare("SELECT * FROM some_table"). I would recommend throwing an exception to see what's going wrong with your connection. You can do this by adding the options to your pdo initialization. array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)
try{
$dbh = new PDO('mysql:host='.MYSQL_HOST.';dbname='.MYSQL_DB,
MYSQL_USERNAME,
MYSQL_PASSWORD,
array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
}catch(Exception $e){
echo $e->getMessage();
}
Hope this helps

var_dump and print_r show nothing, can't check it item exists in Database

I have a PDO that is querying a non-existant user in the database to handle user registration. The problem is, var_dump and print_r both do not print anything if the user is not found.
try {
$stmt->execute();
while($row = $stmt->fetch()) {
var_dump($row);
print_r($row);
if($row = null) { // Not working
# if(!isset($row)) { // Not working
# if(empty($row)) { // Also not working
echo "User not found";
} else {
echo $row['realname']."<br>";
}
}
} catch(PDOException $e) {
echo "FATAL ERROR OCCURED:".$e->getMessage();
}
What is happening here? The page is just blank.
php -l index.php repors no syntax errors and the page is not throwing error 500.
Nothing in view source either.
Here is connection details:
try {
$dbh = new PDO('mysql:host=127.0.0.1;dbname=PHP_PDO', "root", "root", array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
));
} catch(PDOException $e) {
die("FATAL ERROR OCCURED");
}
$stmt = $dbh->prepare("SELECT realname FROM users WHERE name = :name" );
$stmt->bindParam(":name", $name);
$name = "mivuckovaca"; // NOT IN DATA BASE
The reason why it's not working, is that you are "assigning" in if($row = null) using 1 equal sign, rather than "comparing" if($row == null) with 2 equal signs (or 3 "if identical", depending on what you want to check for).
Consult: The 3 different equals here on Stack about this.
References:
http://php.net/manual/en/language.operators.assignment.php
http://php.net/manual/en/language.operators.comparison.php
PHP sees the "assignment" as being valid syntax and that is why you are not receiving any errors.
Turns out i had to reorganize the code a bit.
I took the $row = $stmt->fetch(); out of the while loop, and checked the $row seperately. Like this:
$stmt = $dbh->prepare("SELECT realname FROM users WHERE name = :name" );
$stmt->bindParam(":name", $name);
$name = "mivuckovaca"; // NOT IN DATABSE ON PURPOSE
try {
$stmt->execute();
} catch(PDOException $e) {
echo "FATAL ERROR OCCURED:".$e->getMessage();
}
$res = $stmt->fetchAll(); # Replaced fetch() with fetchAll()
if(empty($res)) {
echo "User not found";
} else {
foreach($res as $row) { # replaced while() with foreach()
echo $row['realname'];
}
}

MySql General error: 2053

I'm getting the error:
ERROR: SQLSTATE[HY000]: General error: 2053
I have no idea why this is happening because the code works fine and the database is updated, but it still returns this error.
Here's my code:
<?php
header("Content-Type: application/json; charset=UTF-8");
require 'UHCauth.php';
try {
$conn = new PDO("mysql:host=$mysql_serv;dbname=$mysql_db", $mysql_user, $mysql_pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
if(isset($_GET['d6518e47'])) {
$USERNAME = $_GET['d6518e47'];
$stmt = $conn->prepare(
"UPDATE $mysql_table
SET KILLS = KILLS+1 WHERE USERNAME = :USERNAME"
);
$stmt->execute(array('USERNAME' => $USERNAME));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
echo json_encode($row);
} else {
$stmt = $conn->prepare(
"SELECT * FROM $mysql_table
ORDER BY
McVersion DESC,
ModVersion DESC
LIMIT 1"
);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
echo json_encode($row);
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
$row = $stmt->fetch(PDO::FETCH_ASSOC); is the line that will cause your error.
Why?
Because there's nothing to fetch - in array - after an update
Remember that
PDO::FETCH_ASSOC: returns an array indexed by column name as returned
in your result set
So, no result set ... no party
If you want to know exit status of your command, just use the return value of execute() function
$rv = $stmt->execute(array('USERNAME' => $USERNAME));

Use of MySQLi within a class

function __construct(mysqli $db, $country = NULL, $sport = NULL) {
$this->db = $db;
$this->country = base64_decode($country);
$this->sport = base64_decode($sport);
}
public function GetColor($colorcode) {
$query = 'SELECT naam_nl FROM colors WHERE code = $colorcode';
$result = $this->db->query($query);
while ($row = $result->fetch_assoc()) { // Line 21
echo $row['naam_nl'];
}
$result->close();
}
Gives me:
Fatal error: Call to a member function fetch_assoc() on a non-object in /home/cloud/public/td/teamdresser.class.php on line 21
So I tried:
$result = $this->db->query($query);
while ($row = $this->db->fetch_assoc($result)) {
echo $row['naam_nl'];
}
And then...
Fatal error: Call to undefined method mysqli::fetch_assoc() in /home/cloud/public/td/teamdresser.class.php on line 21
I'm doing something wrong.. Can someone point me in the right direction?
Like the comments say, you need to do some error checking:
public function GetColor($colorcode) {
$query = 'SELECT naam_nl FROM colors WHERE code = $colorcode';
$result = $this->db->query($query);
if ($result === false) {
// Throw or handle an error here
} else {
while ($row = $result->fetch_assoc()) { // Line 21
echo $row['naam_nl'];
}
$result->close();
}
}
Additionally, you need the mysqlnd drivers: Fatal error: Call to undefined method mysqli_result::fetch_all()
This part is wrong:
public function GetColor($colorcode) {
$query = 'SELECT naam_nl FROM colors WHERE code = $colorcode';
PHP won't interpolate $colorcode when using single quotes. Use double quotes intead:
$query = "SELECT naam_nl FROM colors WHERE code = $colorcode";
Comments:
Always check for the return value! That makes spotting errors much easier.
Why don't you use prepared statements?

Categories