Need help with some php code

General discussions related to php

Moderators: gesf, Michalio

Post Reply
cearlp
New php-forum User
New php-forum User
Posts: 5
Joined: Mon Aug 22, 2022 12:51 pm

What is in error with the following snippet of code?

$y = 0; //counter
$s_first_name = '';
$s_last_name = '';
$s_email = '';

$sql = "select * from members ";

$result = conn($sql);
if (mysqli_num_rows($result)){
echo "<table align='left' cellpadding='0' cellspacing='0'>
<tr><td> </td></tr>
<tr><td style='font-size:16px; font-weight:bold;'>Name.........................</td>";
echo "<td style='font-size:16px; font-weight:bold;'>Email............................................</td>";
echo "</tr>";
//get the values from the db resultset
$count=0;

while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
if ($row["email"] > '') {
// colors white and gray
(($y % 2) == 0) ? $bgcolor = "#ffffff" : $bgcolor = "#c0c0c0";
// colors silver and gray
// (($y % 2) == 0) ? $bgcolor = "#f5f5f5" : $bgcolor = "#c0c0c0";
$s_first_name = $row['fname'];
$s_last_name = $row['lname'];
$s_email = $row['email'];

echo "<tr style='background-color:$bgcolor;'>";
echo "<td>$s_first_name $s_last_name</td>";
echo "<td>$s_email</td>";

$text = "$s_first_name $s_last_name $s_email\n";
fwrite ($enames, $text);
$text = "$s_email\n";
fwrite ($eaddrs, $text);

$count++;
$y++;
}//end if

}//end while

I get the enames and the eaddrs files written with all the members but get only the heading and the first row displayed on the screen.
I know something is wrong but I can't find it.
User avatar
Michalio
Moderator
Moderator
Posts: 265
Joined: Sun Jul 18, 2021 1:33 pm
Location: Poland

Writing to file in a loop is not a good idea, refactor the code to prepare the content for both files and after the loop save each file once
Free coding lessons: https://php-forum.com/phpforum/viewtopic.php?t=29852
cearlp
New php-forum User
New php-forum User
Posts: 5
Joined: Mon Aug 22, 2022 12:51 pm

Thanks for the advice.
I commented out the write statements and get a good listing.
I'll build a table for each and populate them as I loop through the fetch array, and then write the tables to the files after the loop os completed.
cearlp
New php-forum User
New php-forum User
Posts: 5
Joined: Mon Aug 22, 2022 12:51 pm

Couldn't see how to build tables for each file, so I'm at a loss as how to prepare the content for each file.
All the documentation I can find suggests to use fwrite() to write records to a file and then fclose().
User avatar
Michalio
Moderator
Moderator
Posts: 265
Joined: Sun Jul 18, 2021 1:33 pm
Location: Poland

1. Create an empty array for each file
2. Iterate by the row and add the line to the each array
3. Merge the array to string variable
4. Save the variable to the file
Free coding lessons: https://php-forum.com/phpforum/viewtopic.php?t=29852
Post Reply