Jump to content

Recommended Posts

I have this line of code where i want to get the value of SUM(amount)

list($number,$sum) = $this->db->query('SELECT COUNT(*), SUM(amount) FROM dc_donations');

but I get this notice

PHP Notice:  Undefined offset: 1 in C:\www\mvc\models\donate_model.php on line 42

 

At the moment the table is empty and the amount column is of type float so when i run the query through phpMyAdmin it comes back with NULL for the amount.

 

I need that amount for this line so if the table is empty, it's obviously 0

// Calculating how many percent of the goal were met:
$percent = round(min(100*($sum/GOAL),100));
Link to comment
https://forums.phpfreaks.com/topic/283587-php-notice-undefined-offset-1/
Share on other sites

Yeah man, you need to populate your table in order to fetch the data needed for the array.

And undefined offset almost always means that you are trying to access an un-existing element of an array. Like an accessing $array[3] while $array having only 2 elements will generate the same error.

also... unless you have some kind of custom coding.. $this->db->query() will almost certainly be returning a result source, not an array of values to pass to list. You will probably need to use something like $this->db->fetch_array() or similar.

Is $this->db->query() a custom method of a custom database class? In the mySql extensions, the query() method returns a resource (or object) that must be used with one of the fetch_*() functions (or methods).

 

The "undefined offset 1" error is because

list($number,$sum) = $this->db->query('SELECT COUNT(*), SUM(amount) FROM dc_donations');

// Is essentially the same as:
$temp = $this->db->query('SELECT COUNT(*), SUM(amount) FROM dc_donations');
$sum = $temp[1];
$number = $temp[0];
(yes, it assigns from right to left).

 

So the error means that method (query()) is NOT returning an array with two elements.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.