Solved

How do I retrieve the individual results of an array?

Posted on 2014-12-02
4
79 Views
Last Modified: 2014-12-05
Here's my function:

public function pref_reference() {

	global $mysqli;

	$sql="select preferences.email, preferences.id as pref_id, preferences.tool_id, preferences.tool_fields, tools.tool_name, tools.id from preferences inner join tools on preferences.tool_id=tools.id where preferences.id='$_GET[id]'";
	if(!$query=$mysqli->query($sql))
		{
			$err='query_failure:'
			.'ERRNO: '
			.$mysqli->errno
			.'ERROR:'
			.$mysqli->error
			.PHP_EOL
			.' QUERY: '
			.$query
			.PHP_EOL;
			trigger_error($err, E_USER_WARNING);
		}
	
		$result_array=array();

	while($row=$query->fetch_array())
		{
		$result_array[]=$row;
		}
		
	return $result_array;

Open in new window


I want to retrieve from this array the email address and the tool id.

So, I've got this:

$new_tool = new ToolAdmin; //call my class

$reference=$new_tool->pref_reference(); // call the above method

Now I want to echo just the email address that's a part of this array. I've tried:

$reference['email_address'], $reference[0] and just about any other combo I can think of. I know I'm missing something, but I can't figure out what.

I know how to do a foreach, but is there a more direct way of just being able to reference specific values within the array?
0
Comment
Question by:brucegust
  • 2
4 Comments
 
LVL 9

Assisted Solution

by:Brian Tao
Brian Tao earned 75 total points
ID: 40477455
$reference is an array of array now. Please try:
$reference[0]["email"]

Open in new window

0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 425 total points
ID: 40477530
Probably want to get away from this notation:

while($row=$query->fetch_array())

You can use the fetch_object() notation instead.  I don't have time to explain it now, but you'll like it better when you start using object-oriented PHP the right way.

I can't test this because we still don't have that test data we've been asking you for, but I think it may be correct in principle.  Please read the comments over carefully and post back if there is anything you don't understand.

<?php
// ALWAYS SET ERROR_REPORTING LEVEL AS HIGH AS POSSIBLE
error_reporting(E_ALL);


// DO NOT MAKE $mysqli GLOBAL - INSTEAD USE DEPENDENCY INJECTION
public function pref_reference($mysqli) 
{
    // ALWAYS ESCAPE ANY EXTERNAL DATA THAT GETS USED IN A QUERY STRING
    $id 
    = !empty($_GET['id'])
    ? $mysqli->real_escape_string($_GET['id'])
    : NULL
    ;
    
    // CONSTRUCT A QUERY STRING USING THE ESCAPED VARIABLE
    // HOW MANY ROWS DO YOU EXPECT?  MAYBE IT WOULD BE WISE TO
    // SET THE LIMIT CLAUSE TO ENSURE THAT YOU ONLY GET ONE ROW?  
    $sql = 
   "SELECT preferences.email AS e
    , preferences.id AS pref_id
    , preferences.tool_id
    , preferences.tool_fields
    , tools.tool_name
    , tools.id 
    FROM preferences INNER JOIN 
    tools ON preferences.tool_id = tools.id 
    WHERE preferences.id = '$id'
    LIMIT 1
    "
    ;
    
    // USE A MORE MEANINGFUL NAME FOR THE RESULT OBJECT
    if(!$result = $mysqli->query($sql))
    {
        $err='query_failure:'
        . 'ERRNO: '
        . $mysqli->errno
        . 'ERROR:'
        . $mysqli->error
        . PHP_EOL
        . ' QUERY: '
        . $query
        . PHP_EOL
        ;
        trigger_error($err, E_USER_WARNING);
    }

    // THIS IS DONE WITH THE UNDERSTANDING THAT YOU EXPECT ONE ROW	
    if ($row = $result->fetch_object()) return $row;
    return FALSE;
}

// FIND THE EMAIL ADDRESS IN THE ROW OBJECT
var_dump($row->e);

Open in new window

0
 

Author Comment

by:brucegust
ID: 40483301
I figured it out, guys! Not sure if this is the most elegant way to pull it off, but it worked...

$stage_one = strstr($statement, ')', true); //shows everything to the left of the second parenthesis
 $stage_two=strstr($stage_one, '('); //gets rid of the "insert into table_name" verbiage
 $stage_three = ltrim($stage_two, "("); //trims the "(" from the left end of the string
$array = explode(',', $stage_three); //breaks up the remaining string into an array based on the comma between each value
 return $array;

Open in new window


"statement" is the actual insert statement stored in the database as part of the user's preferences. I then used the sequence of $stage_one, $stage_two, etc to break the code down so the only thing remaining was the field headings within that insert statement that could then be shaped as an array.

I then used this:

$statement=new User;
	$statement_array=$statement->table_fields($_POST['tool_id']);
	
	foreach ($the_header as $value)
	{
	$body .='
	<tr><td class="csv_sample_cell"><input type="text" size="35" value="'.$value.'" name="column_'.$the_count.'"></td>
	<td class="csv_sample_cell">
		<select name="select_name_'.$the_count.'">
		<option selected>'.$statement_array[$the_count].'</option>';
		foreach($columns as $row)
		{
			if($row=="session_id")
			{
			continue;
			}
			else
			{
			$body.='<option>'.$row.'</option>';
			}
		};
		$body .='</select>
		</td>
	</tr>';

Open in new window


It works because the array value matches the count of the row that it's listed in.

Thanks, everyone,  as always for weighing in!
0
 

Author Comment

by:brucegust
ID: 40483313
I just realized that I documented the solution for a different question (http://www.experts-exchange.com/Programming/Languages/Scripting/PHP/Q_28572498.html). I'll post that correctly, here in a little bit. Ray, I adopted your solution as well as your suggestion and that solved my problem here.
0

Featured Post

Easy Project Management (No User Manual Required)

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Popularity Can Be Measured Sometimes we deal with questions of popularity, and we need a way to collect opinions from our clients.  This article shows a simple teaching example of how we might elect a favorite color by letting our clients vote for …
Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), the other parts being the altitude and t…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to count occurrences of each item in an array.

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now