<?php
$conn = $mysqli;
$chatarray = array();
$qry = ('SELECT ChatText FROM Chat');
$res = mysqli_query($conn, $qry);
if(mysqli_num_rows($res) > 0) // checking if there is any row in the resultset
{
while($row = mysqli_fetch_assoc($res)) // Iterate for each rows
{
$chatarray[] = $row['ChatText'];
}
}
foreach (array_reverse($chatarray) as $chat)
{
$newmessage = $chat;
$newmessage = nl2br($newmessage);
$newmessage = wordwrap($newmessage, 34, "\n", true);
$bbcode = array("[b]", "[/b]", "[red]", "[blue]", "[green]", "[purple]", "[/color]");
$htmlcode = array("<b>", "</b>", "<span style='color:red'>", "<span style='color:blue'>", "<span style='color:green'>", "<span style='color:purple'>", "</span>");
$newmessage = str_replace($bbcode, $htmlcode, $newmessage);
$btagfixes = "";
$stagfixes = "";
$numbold = substr_count($newmessage, "<b>");
$numboldclosed = substr_count($newmessage, "</b>");
if ($numbold > $numboldclosed)
{
$cnt = $numbold - $numboldclosed;
while ($cnt > 0)
{
$btagfixes .="</b>";
$cnt --;
}
}
$numspan = substr_count($newmessage, "<span");
$numspanclosed = substr_count($newmessage, "</span>");
if ($numspan > $numspanclosed)
{
$cnt = $numspan - $numspanclosed;
while ($cnt > 0)
{
$stagfixes .="</span>";
$cnt --;
}
}
echo "<span class='adv_chat_p'>";
echo $newmessage. "" .$btagfixes. "" .$stagfixes."</span></br></br>";
}