Solved

Generic PHP Class to retrieve values from a table

Posted on 2013-02-02
38
445 Views
Last Modified: 2013-02-02
Experts,

I have made PHP classes to extract data tables, but coding fields for each is tedious.  

I'd like to make a generic Table class that could be easily extended.  I would need to read each row and get the key/value pairs.

Try as I might, the following code only returns one row (not the 31 in the table):
while($row = mysqli_fetch_assoc($res)) {
      foreach($row as $key=>$value) {
      // update the id ...
      $this->id = ($key == $this->pk) ? $value : $this->id;
      // add to the list ...
      $this->list[$this->id]->$key = $key;
      $this->list[$this->id]->$value = $value;
      }
}

Why are the rows not advancing?  How to correct this?

Capt
0
Comment
Question by:Glen Gibb
  • 17
  • 8
  • 7
  • +2
38 Comments
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Maybe this function would be helpful?
http://www.php.net/manual/en/mysqli-result.fetch-all.php
0
 
LVL 82

Expert Comment

by:Dave Baldwin
Comment Utility
mysqli_fetch_assoc() only fetches one row at a time.
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Can you please post the CREATE TABLE statement for the table(s) used in this query, along with the query statement?  It might be helpful to see the rest of the class methods, too.  I am trying to make sense of the $this->id and $this->pk but it's just not working -- too much missing information.

Thanks and regards, ~Ray
0
 
LVL 27

Expert Comment

by:Lukasz Chmielewski
Comment Utility
I think that is not the issue here,

while($row = mysqli_fetch_assoc($res)) {
      foreach($row as $key=>$value) {
...
      }
}

I think this would $this class' values to the last one.
Delete the foreach loop and see if that works
(switch the $key / value to $row['yourdata'])

while($row = mysqli_fetch_assoc($res)) {

      // update the id ...
      $this->id = ($key == $this->pk) ? $value : $this->id;
      // add to the list ...
      $this->list[$this->id]->$key = $key;
      $this->list[$this->id]->$value = $value;

}
0
 
LVL 27

Assisted Solution

by:Lukasz Chmielewski
Lukasz Chmielewski earned 125 total points
Comment Utility
An additional note:
That should advance, the double loop kills that $row retrieving, getting the last one's $key $value pair
0
 

Author Comment

by:Glen Gibb
Comment Utility
Glad to have your responses, Experts.

Ray, I don't have mysqli_fetch_all as a legitimate php function.  What am I missing?

Dave, I realize that mysqli_fetch_assoc retrieves one row at a time.  However, shouldn't the while loop iterate all the rows in the outer loop?

The inner loop is killing the process.  Somehow the row pointer gets hatched by the inner loop and only executes once.
0
 

Author Comment

by:Glen Gibb
Comment Utility
As proof of concept, here's a debug output using echo ++$i on the outer loop:
 -- ID: 1, ID: 2, ID: 3, ..., ID: 31

Here's the output re-instating the inner loop:
List Key: equipmentPK, Val: 1
List Key: eq_typeFK, Val: 4
List Key: mat_typeFK, Val: 1
List Key: gps_lat, Val: 50.123456
List Key: gps_lon, Val: -112.123456
List Key: exact, Val: on
List Key: legal_loc, Val: NW 15-12-4-W4
List Key: eq_desc, Val: new installation
List Key: date_install, Val: 2011-03-01
List Key: corpFK, Val: 3
List Key: eq_statusFK, Val: 1
List Key: poolFK, Val: 15

******************************

Final note:  there are 13 fields.  Not sure why the image (blob) field is not part of the list.
0
 
LVL 27

Expert Comment

by:Lukasz Chmielewski
Comment Utility
if you want to do it like this, try

while($row = mysqli_fetch_assoc($res)) {
      $rows[] = $row;
}

foreach($rows as $key=>$value) {
      // update the id ...
      $this->id = ($key == $this->pk) ? $value : $this->id;
      // add to the list ...
      $this->list[$this->id]->$key = $key;
      $this->list[$this->id]->$value = $value;
}

Open in new window

0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Where does $this->pk come from?  Why does it get compared to $key?

Regarding mysqli_fetch_all() I would guess that you're missing PHP 5.3, which is now in its sunset days.  Current is PHP 5.4, so it's probably time to upgrade.  If you're at a level below PHP 5.3 you're not getting any updates, not even to patch security holes (yikes).
0
 

Author Comment

by:Glen Gibb
Comment Utility
Roads, I think you have the answer.  The foreach wrecks the iterator.

But the problem is, what do you mean by "yourdata"?

I know I can access the info by $row['equipmentPK'] or $row['date_install'], ....

But I need to handle this generically -- I don't know what field values are going to be included in every table.  I need to get those values from the dataset.

How?
0
 

Author Comment

by:Glen Gibb
Comment Utility
Ray, here's the sql:

CREATE TABLE IF NOT EXISTS `equipment` (
  `equipmentPK` int(11) NOT NULL auto_increment,
  `eq_typeFK` int(11) NOT NULL default 0,
  `mat_typeFK` int(11) not null default 0,
  `gps_lat` varchar(25) NOT NULL default '',
  `gps_lon` varchar(25) NOT NULL default '',
  `legal_loc` varchar(15) default null,
  `eq_desc` varchar(25) NOT NULL default '',
  `date_install` date NOT NULL default '0000-00-00',
  `corpFK` int(11) NOT NULL default '0',
  `statusFK` int(11) NOT NULL default '0',
  `poolFK` int(11) NOT NULL default '0',
  `image` blob,
  PRIMARY KEY  (`equipmentPK`),
  FOREIGN KEY  (eq_typeFK) REFERENCES equipment_type(typePK)  ON DELETE cascade ON UPDATE cascade,
  FOREIGN KEY  (mat_typeFK) REFERENCES material_type(typePK)  ON DELETE cascade ON UPDATE cascade
) FOREIGN KEY  (corpFK) REFERENCES corporation(corpPK)  ON DELETE cascade ON UPDATE cascade,
  FOREIGN KEY  (statusFK) REFERENCES equipment_status(statusPK)  ON DELETE cascade ON UPDATE cascade,
  FOREIGN KEY  (poolFK) REFERENCES pool(poolPK)  ON DELETE cascade ON UPDATE cascade,
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
0
 
LVL 27

Expert Comment

by:Lukasz Chmielewski
Comment Utility
Well, then if you don't know what's gonna be as a key and value, then the class variables have to be set in the second loop.
0
 

Author Comment

by:Glen Gibb
Comment Utility
Tnx, Roads.

I guess I'm dense.  Can you give me some pseudo-code to illustrate what you mean?
0
 
LVL 82

Expert Comment

by:Dave Baldwin
Comment Utility
Your 'inner loop' with the 'foreach' contributes nothing to the process.  The 'while' loop with the 'mysqli_fetch_assoc' takes care of it.  mysqli_fetch_all is only available starting with PHP 5.3.

http://www.php.net/manual/en/mysqli-result.fetch-all.php
0
 
LVL 27

Expert Comment

by:Lukasz Chmielewski
Comment Utility
0
 
LVL 27

Expert Comment

by:Lukasz Chmielewski
Comment Utility
@DaveBaldwin
IMO the inner loop overwrites the class properties with each fetched row, having the last one written to the class...
0
 

Author Comment

by:Glen Gibb
Comment Utility
Roads -- were you trying to post a link to useful pseudo-code?  It loops back to this page!
0
 

Author Comment

by:Glen Gibb
Comment Utility
BTW, my PHP version is 5.3.10
0
 
LVL 27

Expert Comment

by:Lukasz Chmielewski
Comment Utility
I was trying to point you to the code I posted before, it's not pseudo-code, it's the code itself ! :)
Try replacing the while with foreach loop with the one pointed.
0
Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

 

Author Comment

by:Glen Gibb
Comment Utility
To complete Ray's request, the sql statement is pretty basic:  SELECT * FROM equipment.

The three classes involved in the process are attached.
database.class.php
table.class.php
equipment.class.php
0
 

Author Comment

by:Glen Gibb
Comment Utility
Roads, I tried the code in the snippet.  All the key / value output is blank!
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
If you run phpinfo() and look at the output you should be able to confirm your PHP Version.  According to this man page, the mysqli_fetch_all() function is available if your PHP is 5.3+ so that makes me wonder why you would not be able to use it.  How did you find out that you do not have this as a legitimate function?

Have you got error_reporting(E_ALL) set?  If not, set it and try things again.  You might find that the script relies on an undefined variable.
0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 200 total points
Comment Utility
In table.class.php the only assignment I can find for $this->pk is on line 11 where it is set to NULL.  In equipment.class.php (extends table) the value is set on line 6 to a literal string with this:

var $pk = "equipmentPK";

So here is what I would do: Follow the variables.  The output will be easier to read in the "view source" of the rendered page.

// FOLLOW THE VARS
var_dump($this->pk);
var_dump($this->id);

// RETRIEVE ONE ROW FROM THE DATA BASE ON EACH ITERATION
while($row = mysqli_fetch_assoc($res)) 
{
    var_dump($row);
    
    // ITERATE OVER THE COLUMNS OF THE ROW
    foreach($row as $key=>$value) 
    {
        var_dump($key, $value);
        
        // IF THE KEY MATCHES 'equipmentPK' ASSIGN $value TO $this->id ELSE LEAVE $this->id ALONE
        $this->id = ($key == $this->pk) ? $value : $this->id;
        
        var_dump($this->id);
        
        // IF $this->id WAS LEFT ALONE, THIS WILL OVERWRITE AN ARRAY POSITION IN $this->list
        $this->list[$this->id]->$key = $key;
        $this->list[$this->id]->$value = $value;
        
        var_dump($this->list);
    }
}

Open in new window

I would also test mysqli_fetch_all() to see if it works.  Trust but verify :-)
0
 

Author Comment

by:Glen Gibb
Comment Utility
Tnx, Ray.  Changing mysqli_fetch_assoc to mysqli_fetch_all breaks the code.  

Error -- call to undefined function mysqli_fetch_all() in line 52 of the database class.

I got the php version 5.3.10 from phpinfo(), and the latest upgrade to my Ubuntu box only gives me that flavour.  Dunno why no fetch_all exists.
0
 
LVL 82

Assisted Solution

by:Dave Baldwin
Dave Baldwin earned 125 total points
Comment Utility
I see what you're doing now.  I never do that, write 'generic' code to try to cover all possibilities.  Things like 'formmail' and 'formmailphp' get dumped when I run into them.  Yes, that means that I write a lot more code (and feel like a secretary typing at times) but I know what I have when I'm done.
0
 

Author Comment

by:Glen Gibb
Comment Utility
Dave, you're probably right.  And if I had spent the time coding that I have trying to solve this tiny little problem, I'd have all my data objects built by now!

Nevertheless, I'd like to know what to do to parse the data from a row.  

Following Ray's "var_dump" procedure, I can pull in all the data in the table.  It's there in the associative array.  Don't actually need mysqli_fetch_all(), because I can GET all the data in the table!

If I add the inner loop to parse a row, it stalls after one iteration.

HOW can I retrieve the data from the fields?  It is there!  The var dump proves it.  But how to get the key / value pairs?
0
 

Author Comment

by:Glen Gibb
Comment Utility
Get the key / value pairs from the columns, I mean.
0
 
LVL 33

Expert Comment

by:Slick812
Comment Utility
greetings capt_alberta, you may be trying to do to many conditions in the inner loop (foreach) -

foreach($row as $key=>$value) {
      $this->id = ($key == $this->pk) ? $value : $this->id;
      $this->list[$this->id]->$key = $key;
      $this->list[$this->id]->$value = $value;
      }

it looks to me the $this->id is the problem here, , I am not sure of the way you use the  $this->list[] array or how you might use it to see (echo) your results, But as far as I can see you need another method of data entry into the  $this->list[] array, Also you mix and match array and object methods here, you may consider using mostly one or the other, sometimes with mixing I can lose thinking about what's what, when, and where, in code (obj? or array? ).

keeping with the $this->list[] as an array you might try

foreach($row as $key=>$value) {
      //$this->id = ($key == $this->pk) ? $value : $this->id;
// I can NOT tell what the above line is suppose to do, but it seems to defeat your purpose here
// as far as I know, if you use $this->list[$this->id]->$key = $key;   you must first create an object in $this->list[$this->id]
// which I do Not see happening in code

//I use $this->list[] as a empty php array, and add an element on each loop
      $this->list[] = "key= ".$key." value= ".$value;
// I have combined the key and value into ONE line for array entry
// once you see that you are getting ALL the correct key-value , then you can do simalar methods to separate the Key values
      }

now to see what you got in $this->list[]
foreach($this->list as $key=>$value) {
echo "row number ".$key."  has K-V as ".$value."<br />";
}

Ok that's my opinion on this setup
0
 
LVL 33

Assisted Solution

by:Slick812
Slick812 earned 50 total points
Comment Utility
oh, if your while loop has more than one loop, you may need to multiply the array depth

$aCount = 0;
while($row = mysqli_fetch_assoc($res)) {
$this->list[$aCount] = array();
++$aCount;
      foreach($row as $key=>$value) {
      $this->list[$aCount][] = "key= ".$key." value= ".$value;
      }
}


foreach($this->list as $wk=>$value) {
foreach($value as $key=>$value) {
echo $wk." -while no. | row number ".$key."  has K-V as ".$value."<br />";
}
0
 

Author Comment

by:Glen Gibb
Comment Utility
Thanks for you efforts, everyone.  I just can't get it.  

I'm going back to hand-coding every single data object.  So much for inheritance.
0
 

Author Closing Comment

by:Glen Gibb
Comment Utility
For anyone following this thread, there is no positive outcome.  It seems you can't get column values without a list of field names.

The inner loop only executes once.  That's all.
0
 
LVL 33

Expert Comment

by:Slick812
Comment Utility
OK,
 I did this code on my server , and it works for me, used ALL Objects for this -

echo 'SELECT OUTPUT BELOW -<br />';
		$query = 'SELECT name, age, current, date1 FROM rank';
	if ($result = $mysqli->query($query)) {echo 'Number returned rows: '.$result->num_rows.'<br>';
	$list = new stdClass;
	$num = 0;
		while ($row = $result->fetch_object()) {
		$str = 'row'.$num++;
		$list->$str = clone $row;
		//echo 'name= ',$row->name,' age= ',$row->age,' current= ',$row->current,' date1= ',$row->date1,'<br>';
		}
		}
		
	$mysqli->close(); // do not need it any more, all in $list

	foreach($list as $wk=>$val) {
		echo $wk;
		foreach($val as $key=>$value) {
			echo " cn ".$key." cv as ".$value." | ";
			}
		echo "<br />";
		}

Open in new window

0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
... you can't get column values without a list of field names.
Not sure I agree with that.  If I have time to give you an example, I'll post it here.  I am not sure from reading your code what kind of data structure you want to achieve, but I know what I might want to get and I can show you that.  The query will return a results set, row-by-row in the form of an associative array or an object.  The only structure that makes sense to me would be an array that contained these associative arrays or objects (I'd prefer the latter).

As to this: Changing mysqli_fetch_assoc to mysqli_fetch_all breaks the code. Well it sounds like at least part of the PHP 5.3 version of the extension was not installed correctly.  If you want to pursue it you might search PHP bugs for more information.

Thanks for the points, ~Ray
0
 

Author Comment

by:Glen Gibb
Comment Utility
Always appreciate your input, Ray.  I know that I'm in good hands when you're on the case.

I found the problem!

The last field of the table was "image" of type "blob".  The inner loop would break when it tried to assign an empty value to $this->list[$this-id]->value -- and never finish.

Testing for the empty value allowed the loop to complete, and voilà!

By the way, you mentioned once that you have students?  Where do you teach?
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Please see http://www.laprbass.com/RAY_temp_capt_alberta.php

The interesting parts start after line 200, but notice that on line 149 I used SELECT * to make the columns anonymous for the rest of the script.  In real life I would never code SELECT * but it makes sense for this demonstration.  

Put your own DB credentials in lines 38-43 and you should be able to run this with very little modification.  Please post back if you have any questions.

<?php // RAY_temp_capt_alberta.php
ini_set('display_errors', TRUE);
error_reporting(E_ALL);
echo '<pre>';


// THIS IS DERIVED FROM A TEACHING EXAMPLE IN USE AT BOSTON UNIVERSITY CDIA
// MAN PAGE: http://php.net/manual/en/mysqli.overview.php
// MAN PAGE: http://php.net/manual/en/class.mysqli.php
// MAN PAGE: http://php.net/manual/en/class.mysqli-stmt.php
// MAN PAGE: http://php.net/manual/en/class.mysqli-result.php
// MAN PAGE: http://php.net/manual/en/class.mysqli-warning.php
// MAN PAGE: http://php.net/manual/en/class.mysqli-sql-exception.php <-- DID NOT WORK PHP 5.3+, MySQL 5.1+
// MAN PAGE: http://php.net/manual/en/mysqli.construct.php
// MAN PAGE: http://php.net/manual/en/mysqli.real-escape-string.php
// MAN PAGE: http://php.net/manual/en/mysqli.query.php
// MAN PAGE: http://php.net/manual/en/mysqli.errno.php
// MAN PAGE: http://php.net/manual/en/mysqli.error.php
// MAN PAGE: http://php.net/manual/en/mysqli.insert-id.php
// MAN PAGE: http://php.net/manual/en/mysqli-result.num-rows.php
// MAN PAGE: http://php.net/manual/en/mysqli-result.fetch-array.php
// MAN PAGE: http://php.net/manual/en/mysqli-result.fetch-object.php


// CREATE AN ARRAY OF NAMES TO USE FOR TEST DATA
$test_names_arrays = array
( array( "fname" => "Walter" , "lname" => "Williams" )
, array( "fname" => "Ray"    , "lname" => "Paseur"   )
, array( "fname" => "Bill"   , "lname" => "O'Reilly" )
, array( "fname" => "Ray"    , "lname" => "Capece"   )
, array( "fname" => "Ray"    , "lname" => "Bradbury" )
, array( "fname" => "John"   , "lname" => "Paseur"   )
, array( "fname" => "Ray"    , "lname" => "Lewis"    )

)
;

// DATABASE CONNECTION AND SELECTION VARIABLES - GET THESE FROM YOUR HOSTING COMPANY
$db_host = "localhost"; // PROBABLY THIS IS OK
$db_name = "??";
$db_user = "??";
$db_word = "??";
require_once('RAY_live_data.php');


// OPEN A CONNECTION TO THE DATA BASE SERVER AND SELECT THE DB
$mysqli = new mysqli($db_host, $db_user, $db_word, $db_name);


// DID THE CONNECT/SELECT WORK OR FAIL?
if ($mysqli->connect_errno)
{
    $err
    = "CONNECT FAIL: "
    . $mysqli->connect_errno
    . ' '
    . $mysqli->connect_error
    ;
    die($err);
}


// SHOW WHAT THE DB CONNECTION OBJECT LOOKS LIKE
var_dump($mysqli);
echo PHP_EOL;


// CREATING A TABLE FOR OUR TEST DATA
$sql
=
"
CREATE TEMPORARY TABLE my_table
( id    INT         NOT NULL AUTO_INCREMENT PRIMARY KEY
, fname VARCHAR(24) NOT NULL DEFAULT ''
, lname VARCHAR(24) NOT NULL DEFAULT ''
)
"
;

// RUN THE QUERY TO CREATE THE TABLE
$res = $mysqli->query($sql);

// IF mysqli::query() RETURNS FALSE, LOG AND SHOW THE ERROR
if (!$res)
{
    $err
    = "QUERY FAIL: "
    . $sql
    . ' ERRNO: '
    . $mysqli->errno
    . ' ERROR: '
    . $mysqli->error
    ;
    error_log($err);

    // HANDLE THE PROGRAMMATIC CONSEQUENCES HERE
    die($err);
}
else
{
    // SHOW THE RESULTS OBJECT
    var_dump($res);
    echo PHP_EOL;
}


// LOADING OUR DATA INTO THE TABLE
foreach ($test_names_arrays as $person)
{
    // ESCAPE THE DATA FOR SAFE USE IN A QUERY
    $safe_fn  = $mysqli->real_escape_string($person['fname']);
    $safe_ln  = $mysqli->real_escape_string($person['lname']);

    // CONSTRUCT THE QUERY USING THE ESCAPED VARIABLES
    $sql = "INSERT INTO my_table ( fname, lname ) VALUES ( '$safe_fn', '$safe_ln' )";

    // RUN THE QUERY TO INSERT THE ROW
    $res = $mysqli->query($sql);

    // IF mysqli::query() RETURNS FALSE, LOG AND SHOW THE ERROR
    if (!$res)
    {
        $err
        = "QUERY FAIL: "
        . $sql
        . ' ERRNO: '
        . $mysqli->errno
        . ' ERROR: '
        . $mysqli->error
        ;
        error_log($err);

        // HANDLE THE PROGRAMMATIC CONSEQUENCES HERE
        die($err);
    }

    // GET THE AUTO_INCREMENT ID OF THE RECORD JUST INSERTED
	$id  = $mysqli->insert_id;
    echo "MySQLI INSERTED A ROW CONTAINING <b>$safe_fn $safe_ln</b> WITH AUTO_INCREMENT ID = $id" . PHP_EOL;
}
echo PHP_EOL;


// CREATE AND SEND A SELECT QUERY AND TEST THE RESULTS
$fname    = "RAY";
$safe_fn  = $mysqli->real_escape_string($fname);

// CONSTRUCT THE QUERY USING THE ESCAPED VARIABLE
$sql = "SELECT * FROM my_table WHERE fname='$safe_fn' ORDER BY lname, fname";
$res = $mysqli->query($sql);

// IF mysqli_query() RETURNS FALSE, LOG AND SHOW THE ERROR
if (!$res)
{
    $err
    = "QUERY FAIL: "
    . $sql
    . ' ERRNO: '
    . $mysqli->errno
    . ' ERROR: '
    . $mysqli->error
    ;
    error_log($err);

    // HANDLE THE PROGRAMMATIC CONSEQUENCES HERE
    die($err);
}
// IF WE GET THIS FAR, THE QUERY SUCCEEDED AND WE HAVE A RESULT OBJECT IN $res
// AND SO WE CAN NOW USE $res IN OTHER MYSQLI FUNCTIONS


// DETERMINE HOW MANY ROWS OF RESULTS WE GOT
$num     = $res->num_rows;
$num_fmt = number_format($num);
if (!$num)
{
    echo "<br/>QUERY: $sql";
    echo "<br/>FOUND NO DATA: ";
    echo PHP_EOL;
}
else
{
    echo "<br/>QUERY: $sql";
    echo "<br/>FOUND $num_fmt ROWS OF DATA ";
    echo PHP_EOL;
}
echo PHP_EOL;


// ITERATE OVER THE RESULTS SET ROWS AS OBJECTS TO SHOW WHAT WE FOUND
echo "USING MySQLi_Result::Fetch_<i>Object</i>(): ";
echo PHP_EOL;
while ($row = $res->fetch_object())
{
    // ROW BY ROW PROCESSING IS DONE HERE
    print_r($row);
    echo PHP_EOL;
}
echo PHP_EOL;



/* ****************** USING A NUMERIC INDEX */
// RESET THE RESULTS SET POINTER TO THE TOP
$res->data_seek(0);

// COLLECT ALL THE ROWS IN AN INDEXED ARRAY
$rows = array();

// THIS IS THE COLUMN NAME WE CAN USE FOR THE ARRAY INDEX
$mark = 'id';

// ITERATOR FOR EACH OF THE ROWS
while ($row = $res->fetch_object())
{
    // ITERATOR FOR EACH OF THE COLUMNS
    foreach ($row as $key => $value)
    {
        // FIND THE MARKER COLUMN NAME
        if ($key == $mark) $rows_key = $value;
    }
    // SAVE THIS ROW INDEXED BY THE MARKER COLUMN VALUE
    $rows[$rows_key] = $row;
}

// SHOW THE COLLECTION OF ROWS
print_r($rows);
echo PHP_EOL;



/* ****************** USING AN ASSOCIATIVE STRING INDEX */
// RESET THE RESULTS SET POINTER TO THE TOP
$res->data_seek(0);

// COLLECT ALL THE ROWS IN AN INDEXED ARRAY
$rows = array();

// THIS IS THE COLUMN NAME WE CAN USE FOR THE ARRAY INDEX
$mark = 'lname';

// ITERATOR FOR EACH OF THE ROWS
while ($row = $res->fetch_object())
{
    // ITERATOR FOR EACH OF THE COLUMNS
    foreach ($row as $key => $value)
    {
        // FIND THE MARKER COLUMN NAME
        if ($key == $mark) $rows_key = $value;
    }
    // SAVE THIS ROW INDEXED BY THE MARKER COLUMN VALUE
    $rows[$rows_key] = $row;
}

// SHOW THE COLLECTION OF ROWS
print_r($rows);
echo PHP_EOL;



/* ****************** SHOWING AN INDEX COLLISION */
// RESET THE RESULTS SET POINTER TO THE TOP
$res->data_seek(0);

// COLLECT ALL THE ROWS IN AN INDEXED ARRAY
$rows = array();

// THIS IS THE COLUMN NAME WE CAN USE FOR THE ARRAY INDEX
$mark = 'fname';

// ITERATOR FOR EACH OF THE ROWS
while ($row = $res->fetch_object())
{
    // ITERATOR FOR EACH OF THE COLUMNS
    foreach ($row as $key => $value)
    {
        // FIND THE MARKER COLUMN NAME
        if ($key == $mark) $rows_key = $value;
    }
    // SAVE THIS ROW INDEXED BY THE MARKER COLUMN VALUE
    $rows[$rows_key] = $row;
}

// SHOW THE COLLECTION OF ROWS
print_r($rows);
echo PHP_EOL;

Open in new window

Best regards, ~Ray
0
 

Author Comment

by:Glen Gibb
Comment Utility
Thanks a bunch!  And I'd still like to know where you teach -- you're the best!
0
 

Author Comment

by:Glen Gibb
Comment Utility
Whoops -- if I'd read I'd realize that's in Boston.  Lucky students.
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Hey, just saw the "blob" thing.  I'd say you've added one more compelling argument to the list of reasons to store the URL of the blob instead of the blob itself! ;-)

I teach at the Boston University Center for Digital Imaging Arts.  We have campuses in Waltham, Atlanta and Georgetown.
0

Featured Post

Zoho SalesIQ

Hassle-free live chat software re-imagined for business growth. 2 users, always free.

Join & Write a Comment

Foreword In the years since this article was written, numerous hacking attacks have targeted password-protected web sites.  The storage of client passwords has become a subject of much discussion, some of it useful and some of it misguided.  Of cou…
Introduction Since I wrote the original article about Handling Date and Time in PHP and MySQL (http://www.experts-exchange.com/articles/201/Handling-Date-and-Time-in-PHP-and-MySQL.html) several years ago, it seemed like now was a good time to updat…
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

772 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

10 Experts available now in Live!

Get 1:1 Help Now