Solved

How do I retrieve the individual results of an array?

Posted on 2014-12-02
4
84 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 109

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

Ransomware: The New Cyber Threat & How to Stop It

This infographic explains ransomware, type of malware that blocks access to your files or your systems and holds them hostage until a ransom is paid. It also examines the different types of ransomware and explains what you can do to thwart this sinister online threat.  

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Move wordpress site 3 41
Selecting SUM data from mysql table with PHP 4 20
000webhost.com default error log 1 28
How to change the link of an image using md5 in php ? 3 32
Introduction HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is…
Generating table dynamically is the most common issue faced by php developers.... So it seems there is a need of an article that explains the basic concept of generating tables dynamically. It just requires a basic knowledge of html and little maths…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

810 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