carve23.himd carve23.himd - 7 months ago 11
PHP Question

Display php result after html

I have a

form
where people can search the database for a certain user. When they search for the user and click submit, they're re-directed to a different page and the results are displayed.

My only issue is that the results are being displayed before the required html tags - here's an example of what the page looks like through Inspect Element:

"Bobby123


"
<!DOCTYPE html>
<html>
<body>
</body>
</html>


How do I display the results AFTER the required html tags? How do I set a "set place" for the results to be displayed?

Here's my code:

<?php
if(isset($_POST['submit'])) {
$term = $_POST['search'];
$searchuser = $stmt = $con->prepare("SELECT * FROM users WHERE username LIKE :term");
$stmt->bindValue(':term', '%'.$term.'%');
$stmt->execute();
if($searchuser->rowCount() > 0) {
while($row = $searchuser->fetch()){
$name = $row['username'];
echo $name;
}
}else{
echo 'No results';
}
}
?>

<form method="post" action="results.php">
<input name="search" type="search">
<input type="submit" name="submit">
</form>


The code on results.php simply is:

<!DOCTYPE html>
<html>
<body>
</html>


If possible, I would not like to use coding like Javascript, Jquery, or anything that is run on the client side.

Answer

Instead of

if($searchuser->rowCount() > 0) {
    while($row = $searchuser->fetch()){
    $name = $row['username'];
    echo $name;
}}else{
    echo 'No results';
}
}

use

if($searchuser->rowCount() > 0) {
    $content = "";
    while($row = $searchuser->fetch()){
        $content .= '<p>' . $row['username'] . '</p>';
    }
}else{
    $content = 'No results';
}

Then, in your HTML (where you want the text to display)

<HTML>
<BODY>
<?PHP echo $content; ?>
</BODY>
</HTML>