Page 1 of 1

Strange array problem...

Posted: Wed Feb 26, 2003 7:44 pm
by Jim
I'm using the following code to pull info from a MySQL DB and print it out:

Code: Select all

<?php
//i am assuming all DB connections have been made

$user_query = "SELECT * FROM site_rights WHERE username='$username'";
$table_query = "SHOW FIELDS FROM site_rights";

$user_result = mysql_query($user_query);
$table_result = mysql_query($table_query);

//get the list of fields to check
while ($table = mysql_fetch_array($table_result)) {
	//exclude the username field cause we're not checking it
	if ($table['Field'] != 'username') {
		$fields[] = $table['Field'];
	}
}

$user_fields = mysql_fetch_array($user_result);

//loop through each available field
foreach($fields as $key => $field) {
	if ($user_fields[$field] != 0) {
		//check each fieldname for a non-zero value
		$editable_fields[$field] = $user_fields[$field];
		print_r($editable_fields);
	}
}
?>
It pulls the info properly... but the problem I have is that when it gets the information from a single field in the MySQL db, it resets to the first field, prints it, and then prints the next one.. until it gets through all the fields. L

Like this:

Code: Select all

Array
(
    &#1111;id] =&gt; 1
)
Array
(
    &#1111;id] =&gt; 1
    &#1111;hw] =&gt; 1
)
Array
(
    &#1111;id] =&gt; 1
    &#1111;hw] =&gt; 1
    &#1111;aom] =&gt; 1
)
Array
(
    &#1111;id] =&gt; 1
    &#1111;hw] =&gt; 1
    &#1111;aom] =&gt; 1
    &#1111;ron] =&gt; 1
)
Array
(
    &#1111;id] =&gt; 1
    &#1111;hw] =&gt; 1
    &#1111;aom] =&gt; 1
    &#1111;ron] =&gt; 1
    &#1111;ee] =&gt; 1
)
Array
(
    &#1111;id] =&gt; 1
    &#1111;hw] =&gt; 1
    &#1111;aom] =&gt; 1
    &#1111;ron] =&gt; 1
    &#1111;ee] =&gt; 1
    &#1111;aok] =&gt; 1
)
I was looking at 'foreach' on PHP.net.. and I guess that's my problem. Any solution for this?

Posted: Wed Feb 26, 2003 8:24 pm
by volka
probably I missed the point but excatly is the problem?
In each iteration of foreach it might add an element to $editable_fields and if so it print_rs the whole resulting array $editable_fields.

Posted: Wed Feb 26, 2003 8:28 pm
by Jim
I'd rather not have it print all that info over and over. I'd like to select one line of each of that result and print it.

Posted: Wed Feb 26, 2003 8:39 pm
by volka
then you should place the print_r outside the foreach-loop or print only that specific element in each iteration, e.g.

Code: Select all

foreach($fields as $key => $field) {
   if ($user_fields[$field] != 0) {
      //check each fieldname for a non-zero value
      $editable_fields[$field] = $user_fields[$field];
   }
}
print_r($editable_fields);
or

Code: Select all

if ($user_fields[$field] != 0) {
      //check each fieldname for a non-zero value
      $editable_fields[$field] = $user_fields[$field];
      echo $field, ' => ', $editable_fields[$field], "\n";
   }