Jump to content

Iterating MySQL Table


neridaj

Recommended Posts

Hello,

 

I have a function that is supposed to return the columns and rows from a db table and pass it on to another function for output. I know this is a routine procedure, but I'm still green with multidimensional arrays and haven't quite got my head around it. Here is the code I have:

 

function get_users()
{
  //extract from the database all the user data
  $conn = db_connect();
  $result = $conn->query( "select username, firstname, lastname, email
                          from user");
  if (!$result)
    return false; 

  //create an array of the user data
  $user_array = array();
  for ($count = 1; $row = $result->mysql_fetch_row(); ++$count) 
  {
    $user_array[$count] = $row[0];
  }  
  return $user_array;
}


function display_users($user_array)
{
  // set global variable, so we can test later if this is on the page
  global $user_table;
  $user_table = true;
?>
  <br />
  <form name='user_table' action='delete_users.php' method='post'>
  <table width=300 cellpadding=2 cellspacing=0>
  <?php
  $color = "#000000";
  echo "<tr bgcolor='$color'><td><strong>User</strong></td>";
  echo "<td><strong>Delete?</strong></td></tr>";
  if (is_array($user_array) && count($user_array)>0)
  {
    while ($row = mysql_fetch_array($user_array, MYSQL_ASSOC))
    {
      if ($color == "#cccccc")
        $color = "#ffffff";
      else
        $color = "#cccccc";

      printf ("<tr bgcolor='$color'><td>%s</td><td>%s</td><td>%s</td><td>%s</td>", $row["username"], $row["firstname"], $row["lastname"], $row["email"]);
      
      echo "</tr>"; 
    }
mysql_free_result($user_array);
  }

 

Thanks for any help,

 

Jason

Link to comment
https://forums.phpfreaks.com/topic/93549-iterating-mysql-table/
Share on other sites

I'm not a wizard on arrays but I have found you have to create the array outside the function then call it in the function with "&$my_array" Then it will return your array.

 

So you would have something like this:

//create an array of the user data
$user_array = array();

function get_users($conn,&$user_array)
{
  //extract from the database all the user data
  $conn = db_connect();
  $result = $conn->query( "select username, firstname, lastname, email
                          from user");
  if (!$result)
    return false; 
  for ($count = 1; $row = $result->mysql_fetch_row(); ++$count) 
  {
    $user_array[$count] = $row[0];
  }  
}

 

Hope this helps point you in the right direction...

 

 

Link to comment
https://forums.phpfreaks.com/topic/93549-iterating-mysql-table/#findComment-479388
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.