I have a web page presenting data from my MySQL database. Where there is the word 'flag', I want the image of the flag to replace it. I know what I have done is (clearly) not right, but I am struggling to find a solution (in layman terms).
<?php
require_once "db_config.php";
$sql = "SELECT username, message, time, type FROM notice_board ORDER BY time DESC";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["time"]. " | ". $row["type"]. " | ". $row["message"] . "<br>";
if ($row["type"]="flag")
{
echo '<img width=10 height=10 src="./media/notice_board/flag.png" />';
}
else if ($row["type"]="information")
{
echo '<img width=10 height=10 src="./media/notice_board/info.png" />';
}
else if ($row["type"]="stop")
{
echo '<img width=10 height=10 src="./media/notice_board/stop.png" />';
}
else if ($row["type"]="warning")
{
echo '<img width=10 height=10 src="./media/notice_board/important.png" />';
}
else if ($row["type"]="question")
{
echo '<img width=10 height=10 src="./media/notice_board/question.png" />';
}
}
} else {
echo "There are no new notices as of yet today";
}
?>
CodePudding user response:
=
is the assignment operator, not the equality check operator. Instead you should use the ===
operator. E.g.:
if ($row["type"] === "flag") {
# Here --------^
echo '<img width=10 height=10 src="./media/notice_board/flag.png" />';
}
CodePudding user response:
In addition to the misuse of the single =
rather than ==
or even ===
you might streamline the code a little to reduce duplication
<?php
require_once "db_config.php";
$sql = "SELECT username, message, time, type FROM notice_board ORDER BY time DESC";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
switch( $row["type"] ){
case 'flag':$src='flag.png';break;
case 'information':$src='info.png';break;
case 'stop':$src='stop.png';break;
case 'warning':$src='important.png';break;
case 'question':$src='question.png';break;
default:$src='info.png';break;// a suitable default perhaps
}
printf(
'%s | %s | %s <br /><img width=10 height=10 src="./media/notice_board/%s" />',
$row["time"],
$row["type"],
$row["message"],
$src
);
}
} else {
echo "There are no new notices as of yet today";
}
?>