mysqli_result is not working properly? [duplicate] - php

This question already has answers here:
Fatal error: Call to undefined function mysqli_result()
(2 answers)
Closed 8 years ago.
There is a table 'hit_count' containing only one column 'count' in database in which I am trying to count the hits by user. problem is whenever I am running this code it shows an error message "Fatal error: Call to undefined function mysqli_result()". Please help!!
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require 'connect.inc.php';
function update_count()
{
global $link;
$query = "SELECT `count` FROM `hit_count`";
if($query_run = mysqli_query($link,$query) || die(mysqli_error($link)))
{
echo 'checking control';
$count = mysqli_result($query_run,0,'count');
echo $count;
}
else
{
echo 'Problem Occured!!';
}
}
update_count();
?>

There isn't a mysqli_result function (not that you can't define it, but what for?). There is a mysqli_result Class, and it has static methods that you can call, of course. But I believe you're doing this wrong.
The correct way would be something like
$count=array();
if($query_run = mysqli_query($link,$query) || die(mysqli_error($link))) {
while ($row = $query_run->fetch_array(MYSQLI_ASSOC)) {
$count[]=$row["count"];
}
}
remember that the outcom of mysqli_query will be an iterable object. Don't expect it to return an aggregate value by default.
PD: if you name your columns with reserved words like count, you're gonna have a bad time.

Related

Trying to get property of non-object in on line 20 [duplicate]

This question already has answers here:
How to force PDOStatement->fetchAll to return array of objects?
(3 answers)
Closed 3 years ago.
I'm getting an error and I don't really know where is the issue. Please can anybody show me what is wrong? I would appreciate any assistance, thanks!
Trying to get property of non-object in on line 20
class.php
class PostsData extends dbh {
public function fetchAllPosts() {
$sql = "SELECT * FROM post";
$stmt = $this->connect()->query($sql);
$stmt->execute([]);
$result = $stmt->fetchAll();
return $result;
} }
blog.php
$post_ = new PostsData;
$allposts = $post_->fetchAllPosts();
foreach ($allposts as $post) {
echo $post->post_title; //error
You are not checking if the result returned is null or not. The error would be generated if it is because there will be no property to access altogether.
Consider a print statement in FetchAllPosts function to check if you get any rows returned. That may help narrow down the scope of the error.

PHP Notice Trying to get property of non-object [duplicate]

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 5 years ago.
I seem to be receiving a number of php notices advising 'Trying to get property of non-object'.
I assume it is the way I have structured the mysql statement but I am a little unsure and I am after assistance here.
The function is as follows:-
public function getPreviousBlock($iHeight=0) {
$stmt = $this->mysqli->prepare("
SELECT height
FROM " . $this->block->getTableName() . "
WHERE height < ?
ORDER BY height DESC
LIMIT 1");
if ($this->checkStmt($stmt) && $stmt->bind_param('i', $iHeight) && $stmt->execute() && $result = $stmt->get_result())
return $result->fetch_object()->height;
return $this->sqlError();
}
Any help would be much appreciated.
fetch_object() will return NULL if there are no more rows in the result set. Of course NULL is not an object so you will get this error.
So you need to check for example:
$obj = $result->fetch_object();
if ($obj) {
return $obj->height;
} else {
return null;
}

Fatal error: Call to a member function fetchAll() on boolean in C:\xampp\htdocs\studysite\test.php on line 16 [duplicate]

This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 3 months ago.
I'm trying to create columns in my database ,but when I run the code I get
Fatal error: Call to a member function fetchAll() on boolean on line 16
$con = connect(DNS,USERNAME,PASSWORD);
//columns as arrays that i need to create if it doesn't exist
$columnname = array("urine_re","lab_investigation","a_records","crazy_gus");
$table='anc_hsd';
//function to check if column name exist if not create it
function columnExist($item,$table,$column){
$exists = false;
$sql = "SHOW COLUMNS FROM $table";
$result = $item->query($sql);
$results=$result->fetchAll(PDO::FETCH_COLUMN);
if(in_array($column,$results)){
$exists=true ;
}
if(!$exists){
$sql="ALTER TABLE $table ADD $column INT(30) NULL";
$item->exec($sql);
}
}
//this is where I use the function
foreach($columnname as $key=>$value){
columnExist($con, $table, $value);
}
The query() method can return false if the query fails. It is a good habit to check if there are any results before processing them:
$result = $item->query($sql);
if ($result) {
$results=$result->fetchAll(PDO::FETCH_COLUMN);
}
else {
// Handle errors
}
But that is only error handling and the query still fails. This is most likely because COLUMNS is not the name of a column in your database table.
Your query failed and it returned FALSE. Then you are applying fetchAll() in a boolean value, and this is impossible. Check the result of this query before using the resource $result.
If you want to be a good programmer, don't be naïve. Never assume your function calls, queries and things like that will work. Always consider the possibility they will fail and check it someway.
In this case you should have a protection like:
$sql = "SHOW COLUMNS FROM $table";
$result = $item->query($sql);
if ($result !== FALSE) {
$results=$result->fetchAll(PDO::FETCH_COLUMN);
} else {
// Alternative code telling what to do when the query fails
}
Hope this helps!

PHP: simple mysql query function - cant get it working [duplicate]

This question already has answers here:
How do you debug PHP scripts? [closed]
(30 answers)
Closed 9 years ago.
i know this must be only a small bug, but i cant find it.
My function:
function del_mysql($table,$id)
{
$id = $_GET['id'];
$exec = mysqli_query($con, "delete from $table where id = '$id'");
return $exec;
}
in Code:
if ($_GET['action'] == 'delete')
{
del_mysql("awsome","$id");
}
if make in function:
$id = $_GET['id'];
echo $table;
echo $id;
i get right table and id.
Somebody see the bug?
I removed already the $exec and return part and leave only mysqli_query command. but dont want to work.
The problem is that in your del_mysql function, you are referencing the connection object $con, which does not exist in the scope of the function. Either pass it into the function as a parameter like this:
function del_mysql($table, $id, $con) {
or access it as a global variable like this:
function del_mysql($table, $id) {
global $con;
I hope that helps.
Regards,
Ralfe

Fatal error: Call to a member function fetch_assoc() on a non-object [duplicate]

This question already has answers here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(2 answers)
Closed 3 years ago.
I'm trying to execute a few queries to get a page of information about some images. I've written a function
function get_recent_highs($view_deleted_images=false)
{
$lower = $this->database->conn->real_escape_string($this->page_size * ($this->page_number - 1));
$query = "SELECT image_id, date_uploaded FROM `images` ORDER BY ((SELECT SUM( image_id=`images`.image_id ) FROM `image_votes` AS score) / (SELECT DATEDIFF( NOW( ) , date_uploaded ) AS diff)) DESC LIMIT " . $this->page_size . " OFFSET $lower"; //move to database class
$result = $this->database->query($query);
$page = array();
while($row = $result->fetch_assoc())
{
try
{
array_push($page, new Image($row['image_id'], $view_deleted_images));
}
catch(ImageNotFoundException $e)
{
throw $e;
}
}
return $page;
}
that selects a page of these images based on their popularity. I've written a Database class that handles interactions with the database and an Image class that holds information about an image. When I attempt to run this I get an error.
Fatal error: Call to a member function fetch_assoc() on a non-object
$result is a mysqli resultset, so I'm baffled as to why this isn't working.
That's because there was an error in your query. MySQli->query() will return false on error. Change it to something like::
$result = $this->database->query($query);
if (!$result) {
throw new Exception("Database Error [{$this->database->errno}] {$this->database->error}");
}
That should throw an exception if there's an error...
Most likely your query failed, and the query call returned a boolean FALSE (or an error object of some sort), which you then try to use as if was a resultset object, causing the error. Try something like var_dump($result) to see what you really got.
Check for errors after EVERY database query call. Even if the query itself is syntactically valid, there's far too many reasons for it to fail anyways - checking for errors every time will save you a lot of grief at some point.
I happen to miss spaces in my query and this error comes.
Ex: $sql= "SELECT * FROM";
$sql .= "table1";
Though the example might look simple, when coding complex queries, the probability for this error is high. I was missing space before word "table1".
Please check if you have already close the database connection or not.
In my case i was getting the error because the connection was close in upper line.

Categories