Jump to content

Pull value from array w/ key variable function not working


barocky82

Recommended Posts

Hi Guys,

 

I'm a PHP newbie and I'm having some trouble creating a function that I can call where I can perform a MYSQL SELECT querey which returns an associative array, and be able to pull a value from that array and return it to the call. My code is below. Everything seems to work up until where I try to set the $average variable. If I return $row instead of $round_val, I see me array as "Array ( [user_id] => 64 [AVG(twos_made)] => 5.0000 )" It seems as though my my functions arugment (twos_made - which is my $column_name var) is not getting passed through or something. Any help would be greatly appreciated!

 

Thanks!

 

 

function avg_of($column_name) {
  global $connect_db; 
  $query = "SELECT user_id, AVG($column_name) FROM table GROUP BY user_id";
  $result = mysql_query($query, $connect_db);
  $row = mysql_fetch_assoc($result); 
  $average = $row['AVG($column_name)'];
  $round_val =  round($average, 1); 
  return $round_val;
  
}

Link to comment
Share on other sites

Thanks for the the quick response, Ken! Unfortunately, that didn't do the trick either. Here is what my code looks like now per your request:

 

function avg_of($column_name) {
	global $connect_db;	
	$query = "SELECT user_id, AVG($column_name)as my_avg FROM table GROUP BY user_id";
	$result = mysql_query($query, $connect_db);
	$row = mysql_fetch_assoc($result); 
	$average = $row[' my_avg'];
	$round_val =  round($average, 1);	
	return $row;

 

I'm not getting a zero as the average when it should be '5'. If I return $row instead of $round_val, I get "Array ( [user_id] => 64 [my_avg] => 5.0000 )". For some reason it doesn't seem like the extraction of the 'my_avg' key from the $row array is working. Any other thoughts?

 

Thanks again for you help!

Link to comment
Share on other sites

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.