php - How to assign a span to a certain username -
a solution has been found! thank @northkildonan , @doug leary.
solution code;
if ($result->num_rows > 0) { // output data of each row while($row = $result->fetch_assoc()) { echo "<li class='list-group-item'>" . $row["user_name"]; if ($row["user_name"] == "tacolover22") { echo "<span class='badge'>dev</span>"; } echo "</li>"; }
##
i have list of usernames , have code checks if username exists, if exist, want div appended it. here's image explaining this
however, code have works, doesn't assign div selected username.
here's php code;
<?php if ( $row["user_name"] === "tacolover22");{ echo "<span class='badge'>dev</span>"; } ?>
here's other php code grabs usernames;
<?php $servername = "####"; $username = "####"; $password = "########"; $dbname = "########"; // create connection $conn = new mysqli($servername, $username, $password, $dbname); // check connection if ($conn->connect_error) { die("connection failed: " . $conn->connect_error); } $sql = "select user_name users"; $result = $conn->query($sql); if ($result->num_rows > 0) { // output data of each row while($row = $result->fetch_assoc()) { echo "<li class='list-group-item'>" . $row["user_name"]; } } else { echo "0 results"; } $conn->close(); ?>
the result of code can found here.
edit: here's full code suggestions, still doesn't seem work. span doesn't appear now.
// output data of each row while($row = $result->fetch_assoc()) { echo "<li class='list-group-item'>" . $row["user_name"]; if ($row["user_name"] === "tacolover22") { echo "<span class='badge'>dev</span>"; } echo "</li>"; }
thanks , help.
you have append <span>
inside mysql-fetch-loop (note: talking divs, using span, different in html).
while($row = $result->fetch_assoc()) { echo "<li class='list-group-item'>" . $row["user_name"]; if ($row["user_name"] == "tacolover22") { echo "<span class='badge'>dev</span>"; } }
explanation: iterating resultset of mysql-query right in while-loop. variable $row
pointer points respective row of result.
after while-loop finished, "pointer" show last result row of mysql-query. $row["user_name"]
set last user name found in database. that's why have access inside while-loop.
how handle multiple users (as requested):
decided use switch
instead of if elseif
statements here since it's better read , less write imho:
while($row = $result->fetch_assoc()) { echo "<li class='list-group-item'>" . $row["user_name"]; switch($row["user_name"]) { case "tacolover22": echo "<span class='badge'>dev</span>"; break; case "anotheruser": echo "<span class='badge'>user</span>"; break; } }
Comments
Post a Comment