0 Replies - 1679 Views - Last Post: 08 December 2012 - 01:40 PM

#1 creativecoding   User is offline

  • Hash != Encryption
  • member icon


Reputation: 931
  • View blog
  • Posts: 3,216
  • Joined: 19-January 10

Get associative array of data from mysqli_result object, and prepend k

Posted 08 December 2012 - 01:40 PM

Description: This snippet will fetch data from a mysqli_result object into an associative array. The keys will be in the format of "(table).(column)", making it very useful for queries containing JOINs.

Comment: Call fetchArray with the only argument being a mysqli_result object (if your query failed, it will return a boolean(false)). Returns an array.

When selecting tables in your query, you may use "AS" to rename the table. For example, "SELECT id FROM users AS user" will return an array with single key being "user.id".

Multiple rows will be put into an array, IE:
array(
[0] => (row array)
[1] => (row array)
[2] => (row array)
etc etc
)

        /*
	 * fetchArray(mysqli_result $result)
	 * Fetches an associative array of $result. Array keys are prepended with their respective table names in the format of: (table).(column)
	*/
	public function fetchArray($result){
		$rows = array();
		$fieldcount = $result->field_count;
		$i = 0;
		while($row = $result->fetch_row()){
			for($n = 0; $n < $fieldcount; $n++){
				$meta = $result->fetch_field_direct($n);
				$rows[$i][$meta->table . '.' .  $meta->name] = $row[$n];
			}
			$i++;
		}
                if(count($rows) == 1) $rows = $rows[0];
		return $rows;
	}



Is This A Good Question/Topic? 0
  • +

Page 1 of 1