user130452 user130452 - 10 days ago 5
PHP Question

How to Check If 10 Most Recent Entries in MySQL DB Begin with a String Using PHP?

I want to allow people to write something like BOLD: or ITALIC: at the beginning of their message to make bold or italic. The only way I can think of is to get the total amount of entries by ID and minus 10 then make an IF statement and minus 9 and so on. Is there a single statement I could query to check if the string in the database begins a certain way and display it in HTML in bold or italic if it does?

<?PHP

$A = "localhost"; // Server Name
$B = "root"; // MySQL Username
$C = ""; // MySQL Password
$D = "sql"; // Database

$CONNECT = new mysqli($A, $B, $C, $D);

if ($CONNECT->connect_error) {
die('<DIV>Connection Failed</DIV>');
}

echo "<DIV>Connected</DIV>";

if (isset($_POST['MSG'])) {
$MSG = htmlspecialchars($_POST['MSG']);
$SQL = "INSERT INTO Messages (Message) VALUES ('$MSG')";

if ($CONNECT->query($SQL) === TRUE) {
echo "<DIV>Message Sent</DIV>";
} else {
echo "<DIV>Error Sending Message</DIV>";
}
}

$SELECT = 'SELECT * FROM Messages ORDER BY ID DESC LIMIT 10';
$RESULT = $CONNECT->query($SELECT);

if (mysqli_num_rows($RESULT) > 0) {
while ($ROW = mysqli_fetch_assoc($RESULT)) {
echo '<DIV>ID: ' . $ROW['ID'] . ' MSG: ' . $ROW['Message'] . '</DIV>';
}
}


I added in some code if somebody begins their message with "'", but the type of strpos if statement doesn't work in the while loop for retrieving messages.

if (isset($_POST['MSG'])) {
$MSG = htmlspecialchars($_POST['MSG']);
$SQL = "INSERT INTO Messages (Message) VALUES ('$MSG')";

if ($CONNECT->query($SQL) === TRUE) {
echo "<DIV>Message Sent</DIV>";
} else {
if (substr($MSG,0,1 == '\'')) {
echo "<DIV>Error Sending Message</DIV>";
} else {
echo "<DIV>Nice Try :')</DIV>";
}
}

Answer

In order for this question to have an answer i will sum up what i did in the comments:

if (mysqli_num_rows($RESULT) > 0) {
    while ($ROW = mysqli_fetch_assoc($RESULT)) {
        $message = $ROW['message'];
        if(strpos($ROW['message'], 'BOLD:') !== false){
            $message = substr($ROW['message'], 5);
        } else if(strpos($ROW['message'], 'ITALIC:') !== false){
            $message = substr($ROW['message'], 7);
        }
        echo '<DIV>ID: ' . $ROW['ID'] . ' MSG: ' . $message . '</DIV>';
    }
}