Jump to content

Accessing individual values of an array in a foreach loop?


Conjurer

Recommended Posts

I have a database query set up that returns an array. I then cycle through the rows in a foreach statement that wraps each value in a <td> tag to output it to a table.

 

It works really great, but now I need to access two of the values and add some info to them. The first field returned is an image filename and I want to wrap it in an image tag that also concatenates the image path location to the value. All the images are stored in the same location, so basically I want to take the first value form the array and add the path to where the images are and wrap the whole thing in an <img> tag.

 

The other field I need to modify is the last value in the array which is actually an email address. For that field I want to make them an active email link so I need to wrap an <a>href=mailto: </a> tag around the value.

 

How could I modify this code so I could add the necessary tags to these elements of the array?

 

Here is the code I am running:

$query = "Select
                 member_image as 'Image',
                 member_name as 'Name',
                 city as 'City',
                 phone as 'Phone',
                 email as 'Email'
                 FROM directory";

//connect to database
$conn=db_connect();

//call function do_query to run the query and output the table
do_query($conn, $querey);

The functions called are as follows:

function db_connect()
{

    $conn = new mysqli("localhost", "username", "password", "databasename"); 

}

function do_query($conn, $query);
{

    $result = mysqli_query($conn, $query); 

   WHILE ($row = mysqli_fetch_assoc($result)) 
   { 
     If (!$heading) //only do if header row hasn't been output yet 
     {  $heading = TRUE; //so we only do it once 
         echo "<table>\n<tr<>\n";
         foreach ($row as $key => $val) 
           { echo "<th>$key</th>";
            }
          echo "</tr>\n"; 
      } 
      echo "<tr>"; 
      foreach ($row as $val) 
     {
          echo "<td> $val </td>"; 
      } 
     echo "</tr>\n"; 
} //close the while 
echo "</table>\n"; 

}

Link to comment
Share on other sites

You could expand your second foreach loop to look something like this:

 

<?php

foreach ($row as $key => $val) {
    echo "<td>";
    if ($key == "Image")
        echo "<img src=\"/path/to/images/$val\" />";
    else if ($key == "Email")
        echo "<a href=\"mailto:$val\">$val</a>";
    else
        echo $val;
    echo "</td>"; 
} 

?>

Link to comment
Share on other sites

I would really suggest being more explicit in your code. Instead of using a foreach() loop on the individual fields, explicitly list the fields and the code you want. It makes debugging and modification much easier. Sometimes trying to make your code "simple" causes more trouble than it is worth.

 

The function do_query is written in such a way that you are apparently using it to run/output many different queries. If you take that approach and start implementing if/else statements for each and every possible query it is going to be a nightmare to manage. Just create a function/process for each query/output you want to run. It's better to have more code that is logically structured.

 

Note: I used mysql instead of mysqli functions in the code below because I have them remembered by heart. Modify them as needed.

 

PHP code:

<?php

function db_connect()
{
    $conn = new mysqli("localhost", "username", "password", "databasename");\
}

function do_query($conn, $query)
{
    return mysqli_query($conn, $query);
}

//connect to database
$conn = db_connect();

$query = "Select member_image, member_name, city, phone, email
          FROM directory";

//call function do_query to run the query and output the table
$directoryResult = do_query($conn, $querey);

if(!$directoryResult)
{
    $output = "<tr><td>There was a problem running the query.</td></tr>";
}
elseif(mysql_num_rows($directoryResult))
{
    $output = "<tr><td>There are no records to display.</td></tr>";
}
else
{
    $imgPath = "images/";
    $output  = "<tr>\n";
    $output .= "<th>Image</th>\n";
    $output .= "<th>Name</th>\n";
    $output .= "<th>City</th>\n";
    $output .= "<th>Phone</th>\n";
    $output .= "<th>Email</th>\n";
    $output .= "</tr>\n";
    while($record)
    {
        $output .= "<tr>\n";
        $output .= "<td><img src=\"{$imgPath}{$record['member_image']}\" /></td>\n";
        $output .= "<td>{$record['member_name']}</td>\n";
        $output .= "<td>{$record['city']}</td>\n";
        $output .= "<td>{$record['phone']}</td>\n";
        $output .= "<td><a href=\"mailto:{$record['email']}\">{$record['email']}</td>\n";
        $output .= "</tr>\n";
    }
}

 

Then in the HTML code

<table>
<?php echo $output; ?>
</table>

Link to comment
Share on other sites

Thanks for pointing me in a couple directions.  I think I can figure it out from there, that will be very useful indeed!  And I see the point in the second post, in this case I am only pulling a few elements, but in a larger query it could get messy. 

Link to comment
Share on other sites

I would really suggest being more explicit in your code. Instead of using a foreach() loop on the individual fields, explicitly list the fields and the code you want. It makes debugging and modification much easier. Sometimes trying to make your code "simple" causes more trouble than it is worth.

 

The function do_query is written in such a way that you are apparently using it to run/output many different queries. If you take that approach and start implementing if/else statements for each and every possible query it is going to be a nightmare to manage. Just create a function/process for each query/output you want to run. It's better to have more code that is logically structured.

 

Note: I used mysql instead of mysqli functions in the code below because I have them remembered by heart. Modify them as needed.

 

PHP code:

<?php

function db_connect()
{
    $conn = new mysqli("localhost", "username", "password", "databasename");\
}

function do_query($conn, $query)
{
    return mysqli_query($conn, $query);
}

//connect to database
$conn = db_connect();

$query = "Select member_image, member_name, city, phone, email
          FROM directory";

//call function do_query to run the query and output the table
$directoryResult = do_query($conn, $querey);

if(!$directoryResult)
{
    $output = "<tr><td>There was a problem running the query.</td></tr>";
}
elseif(mysql_num_rows($directoryResult))
{
    $output = "<tr><td>There are no records to display.</td></tr>";
}
else
{
    $imgPath = "images/";
    $output  = "<tr>\n";
    $output .= "<th>Image</th>\n";
    $output .= "<th>Name</th>\n";
    $output .= "<th>City</th>\n";
    $output .= "<th>Phone</th>\n";
    $output .= "<th>Email</th>\n";
    $output .= "</tr>\n";
    while($record)
    {
        $output .= "<tr>\n";
        $output .= "<td><img src=\"{$imgPath}{$record['member_image']}\" /></td>\n";
        $output .= "<td>{$record['member_name']}</td>\n";
        $output .= "<td>{$record['city']}</td>\n";
        $output .= "<td>{$record['phone']}</td>\n";
        $output .= "<td><a href=\"mailto:{$record['email']}\">{$record['email']}</td>\n";
        $output .= "</tr>\n";
    }
}

 

Then in the HTML code

<table>
<?php echo $output; ?>
</table>

 

Just now trying to implement and I don't understand the piece above where it says:

elseif(mysql_num_rows($directoryResult))
{
    $output = "<tr><td>There are no records to display.</td></tr>";
}

 

Don't I just want that when the value is 0 - cause if it is 1 or higher there are rows to display?  So should it be like this instead:

elseif(mysql_num_rows($directoryResult)='0')
{
    $output = "<tr><td>There are no records to display.</td></tr>";
}

 

Thanks for the help!

Link to comment
Share on other sites

Correct, but your syntax is incorrect. First you should use double equal signs to compare two values. Second, you should not enclose the zero in quote marks since you want to compare to the numeric value of zero and not a string with the zero character

elseif(mysql_num_rows($directoryResult)==0)
{
    $output = "<tr><td>There are no records to display.</td></tr>";
}

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.