Reputation: 41
I'm using this code to send data from mysql into email :
$sql = "SELECT * FROM orders ORDER BY id";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0)
{
// append data of each row to $msg.
while($row = mysqli_fetch_assoc($result))
{
$body .= " <style>
table{width:100%}
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 5px;
text-align: left;
}
</style> ".
"<table>".
"<tr> <th> name </th>
<th>last name</th>
<th>email</th>
</tr>".
"<tr>".
"<td>". $row["col1"]. "</td>".
"<td>" . $row["col2"]. "</td>".
"<td>" . $row["col3"]. "</td>".
"</tr>".
"</table>" ;
}
$body = wordwrap($body,70);
mail($to_email, $subject, $body, $headers);
}
else
{
echo "0 results";
}
mysqli_close($conn);
?>
It works fine but the only problem that I'm getting multi tables but I want to display all the rows in single table.
Can anyone tell me what I'm doing wrong or how to fix it ?
Upvotes: 0
Views: 69
Reputation: 83
Assign HTML table tag to body variable outside for loop.
$sql = "SELECT * FROM orders ORDER BY id";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
$body= " <style>
table{width:100%}
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 5px;
text-align: left;
}
</style> <table>";
$body.="<tr>
<th>name</th>
<th>last name</th>
<th>email</th>
</tr>";
while($row = mysqli_fetch_assoc($result)) {
$body.=
"<tr>".
"<td>". $row["col1"]. "</td>".
"<td>" . $row["col2"]. "</td>".
"<td>" . $row["col3"]. "</td>" .
"</tr>";
}
$body.="</table>" ;
$body = wordwrap($body,70);
mail($to_email, $subject, $body, $headers);
} else {
echo "0 results";
}
mysqli_close($conn);
Upvotes: 0
Reputation: 12355
Move the table HTML tags outside of your loop:
<table>
<thead>
<th>Header</th>
</thead>
<tbody>
<?php //put your loop here ?>
</tbody>
</table>
Upvotes: 3