Jump to content

[SOLVED] Build Array Dynamically


willeadie

Recommended Posts

Hello, first post, please bear with me.

 

I'm working with classes, and right now the class attributes are set in an array I have to manually create for each class, as such:

 

protected static $db_fields = array('id', 'username', 'first_name', 'last_name', 'admin_rights', 'hashed_password');

 

What I want to do is have the class attributes array build dynamically from the results of a query to my database.  i can get the array i want through a function, but i'm not able to have these values in the class variable, for some reason.  here's the array function i built (note that $database is a separate class and that $database->query and similar are just database-independent versions of thins like sql queries):

 

	function class_attributes (){
	global $database;
	if($result_set = $database->query("DESCRIBE ".static::$table_name)){
		while($i = mysql_fetch_assoc($result_set)){
			$field = array_shift($i);
			$db_array[] = $field;
		}
		return $db_array;
	}
}

 

When I try to do something like (and yes, i realize this is all wrong here!)

 

protected static $db_fields = $this-> class_attributes ();

 

I get errors like "Parse error: parse error, expecting `T_FUNCTION'"

 

Thoughts?

Link to comment
Share on other sites

ok let me try to understand.. you're going into your database and pulling a row.. and trying to assign the fields as attributes and the values of those fields as the values of the attributes...

 

for example:

 

 

db query returns an array like:

$row['id'] = 19;

$row['name'] = 'timmy';

$row['age'] = 95;

 

you want to transform that into

 

$this->id = 19;

$this->name = 'timmy';

$this->age = 95;

 

if so you'd do something like:

 

foreach ($row as $k => $v) {

  $this->$k = $v;

}

Link to comment
Share on other sites

You dont use global variables within a class!

I have used a similar database wrapper class.  Ammend as needed

<?php
class foo {
private $db;
private $tableName;
public $dbFields = array();

public function __construct($tableName) {
	$this->db = new dbSql();	
	$this->tableName = $tableName;
	$this->fieldNames();
}

private function fieldNames() {
	$this->db->query("SHOW COLUMNS FROM ".$this->tableName);
	$array = array();
	while($row = $this->db->nrecord()) {
		$array[] = $row;
	}
	for($x = 0; $x < count($array); $x++) {
		$this->dbFields[] = $array[$x][0];
	}
}
}

// usage
$x = new foo("myTable");
print_r($x->dbFields);
?>

Link to comment
Share on other sites

The default value for a class variable can only be a literal value (including an empty array), not a variable. You need to assign a value to $db_fields by using some php code at the point you have called the class_attributes() function. (Edit: or see the code neil.johnson just posted.)

Link to comment
Share on other sites

This is a reply to the first response.  I'll look at the second presently.  Looks spot on.

 

 

 

 

 

Not exactly.  Within each class I'm making, I have an array called

 

$db_fields = array('id', 'username', 'first_name', 'last_name', 'admin_rights', 'hashed_password')

 

which values ('id', 'username', etc.--the actual word 'id', NOT some user's unique id) are the attributes for the class. 

 

Right now, I manually create the $db_field array for a class, based on the field names in the db table for that class.  What I want to do is--instead of manually entering those array values like 'id' and 'username'--populate that array based on the field names in the db table.

 

My function outputs those values as so, on a print_r():

 

Array ( [0] => id [1] => first_name [2] => last_name [3] => username [4] => admin_rights [5] => hashed_password )

 

So, how do I go from this to dynamically-building the array.  Again, not any actual values, but the actual string 'id' (or whatever the db table fieldnames are for that particular table)

 

Thanks in advance!

 

 

Link to comment
Share on other sites

<?php

include('connectionInfo.php');

$fields = mysql_list_fields('database','table');

$i = 0;

$db_fields = array();

while ($field = @mysql_field_name($fields,$i++)) {

$db_fields[] = $field;

}

?>

 

you can also use this :)

 

well you'd hafta modify it a bit to work in your class :) and probably don't need to include the connection info I just put that there to show you actually need an active connection :)

Link to comment
Share on other sites

I've never really worked with classes so I couldn't say for that, but as far as dynamically generating an array of field names, I'd personally do something like...

 

<?php
$results = mysql_query("SELECT * FROM `table` LIMIT 1");
$row = mysql_fetch_assoc($results);

$db_fields = array();
foreach($row as $k=>$v) {
  $db_fields[] = $k;
}
?>

 

Looking at neil. johnsons code (EDIT: and RusselReal's), he has used a similar method. I suspect it may be slightly more efficient, but I was previously unaware of the SHOW COLUMNS keywords. I didn't really need to post, but was intruiged as to whether somebody perhaps slightly more in the know could illustate a performance difference between my method and that of neil. johnsons.

Link to comment
Share on other sites

From an educational perspective I looked up RusselReal's function of mysql_list_fields, whilst it works the function is considered deperacated and the suggested replacement is "SHOW COLUMNS FROM `table`" (as used by neil.johnson).

Link to comment
Share on other sites

From an educational perspective I looked up RusselReal's function of mysql_list_fields, whilst it works the function is considered deperacated and the suggested replacement is "SHOW COLUMNS FROM `table`" (as used by neil.johnson).

 

the suggested replacement essentially does the same thing but pushes a ton of extra information where as all he wants is the names :)

Link to comment
Share on other sites

The actual issue in the thread is not how to get the list of column names (there are probably ten different ways, four of which have been posted so far...) but in storing those names in a class variable. The original method did not work because you cannot use a function value or a variable as the default value when a class variable is declared. Whatever method is used to get the column names, must then assign the results to the class variable using php code.

Link to comment
Share on other sites

The actual issue in the thread is not how to get the list of column names (there are probably ten different ways, four of which have been posted so far...) but in storing those names in a class variable. The original method did not work because you cannot use a function value or a variable as the default value when a class variable is declared. Whatever method is used to get the column names, must then assign the results to the class variable using php code.

 

Yes, I wish people understood and viewed other posts!

Link to comment
Share on other sites

The actual issue in the thread is not how to get the list of column names (there are probably ten different ways, four of which have been posted so far...) but in storing those names in a class variable. The original method did not work because you cannot use a function value or a variable as the default value when a class variable is declared. Whatever method is used to get the column names, must then assign the results to the class variable using php code.

 

Indeed.  OK, I looked neil.johnson's code, and I realize what he is doing is changing the array values on instantiation using __construct (running the function).  Is it possible to do this without an instantiation?  Just wondering.

 

OK, i use a global variable ($database) b/c all the db info is in that class.  Ignore that for now b/c it works (or clue me in on it; I can post that class if you want).  So, I adapted the code so that it would work for my stuff, but only the first letter for the name comes into the array for some reason.  Here's the function: 

 

function class_attributes (){
	global $database;
	if($result_set = $database->query("DESCRIBE ".static::$table_name)){
		$db_array = array();
		while($i = mysql_fetch_assoc($result_set)){
			$field = array_shift($i);
			$db_array[] = $field;
		} // (1) at this point I have the right names in the array!

		// this should assign the array values to the $db_fields array
		for($x = 0; $x < count($db_array); $x++) {
			static::$db_fields[] = $db_array[$x][0];
		}
	}
}

 

 

and here's the array (print_r()) at point (1)  [edit--this is what I had already]:

 

Array ( [0] => id [1] => first_name [2] => last_name [3] => username [4] => admin_rights [5] => hashed_password )

 

Here's the array after the for statement [from neil]:

 

Array ( [0] => i [1] => f [2] => l [3] => u [4] => a [5] => h [6] => i [7] => f [8] => l [9] => u [10] => a [11] => h )

 

Thoughts?  Thanks!

Link to comment
Share on other sites

duh, i just cut out the for statement and put in:

 

static::$db_fields = $db_array;

 

so now I output the correct array.

 

Can I change $db_fields without running the function through __construct on instantiate?  Not sure it matters, but may not have an instantiation (so, can i do it on the class, not object, level).

 

thanks!

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.