Echo content within a div?

I am trying to make a simple guestbook page as part of my university project. I have the guestbook able to read and write from a database, however, when I try to display the results at the bottom of the page they appear at the top no matter what I do.

What would I have to do to fix this? A couple of ideas crossed my mind:
Javascript (jQuery is not allowed)
Having the div link to a different webpage. (A webpage inside a webpage?)
Echo various different versions of <div id = “PLEASE WORK”>

But either these don’t work, or I can’t make them work.
Any help would be much appreciated.

Well, this is actually a very trivial issue, but we need some source code to help you out. This is just a matter of where you decide to print your variable int he html document…

code:

 <!DOCTYPE html>
<html>
	<head>
	<link type="text/css" rel="stylesheet" href="css/style1.css"/>
		<title>J.L. Lane Imaginarium</title>
		<!--
		<script language = "JavaScript">
			function charRemaining (field, countfield, maxlimit)
			{
				if (field.value.length > maxlimit)	
				{
					field.value = field.value.substring (0, maxlimit);
				}
				else
				{
					countfield.value = maxlimit - field.value.length;
				}
			}
		</script>
		Minified below
		-->
		<script>
		function charRemaining(e,t,n){if(e.value.length>n){e.value=e.value.substring(0,n)}else{t.value=n-e.value.length}}
		</script>
	</head>
	<body>
	<div class = "contentMain">
	<div id = "connection">
	<?php
			//Check PHP is running
			echo '<img src ="images/php.png" alt ="PHP is running" height="25px" width ="47px">';
			
			//Establish a connection to the database
			$host = "Mysql.*******webserver.co.uk";
			$id = "removed";
			$pwd = "*********";
			$db = "removed";
			$tbl ="guestbookEntry";
			
			$connection = @mysql_connect($host, $id, $pwd);
			
			if($connection)
			{
				echo '<img src ="images/serverSuccess.png" alt = "Connection to server successful" width ="26px" height ="25px">';
			}
			else
			{
				echo '<img src ="images/serverFail.png" alt = "Connection to server unsuccessful" width ="26px" height ="25x">';
			}
			
			$dbconnect = @mysql_select_db($db);
			
			if($dbconnect)
			{
				echo '<img src ="images/databaseSuccess.png" alt = "Connection to databse successful" width ="26px" height ="25px">';
			}
			else
			{
				echo '<img src ="images/databaseFail.png" alt = "Connection to server unsuccessful" width ="26px" height ="25px">';
			}
		?>
	</div>
	
		<h1>J. L. Lane</h1>
		<div id = "navbar">
			<a href ="aboutme.html" alt = "About Me">About me</a>
			<a href ="guestbook.html" alt = "Guestbook">Guestbook</a>
			<a href ="writing.html" alt = "Writing">Writing</a>
			<a href ="art.html" alt = "Art">Art</a>
		</div>
		<br>
		<br>
		<form action = "guestbook.php" method = "post" name = "guestbook">
			<table>
				<tr>
					<td>Name:</td>
					<td><input type ="text" name ="name" size = "38"></td>
				</tr>
				
				<tr>
					<td>E-Mail Address:</td>
					<td><input type = "email" name = "email" size = "38"></td>
				</tr>
				
				<tr>
					<td valign = "top">Comment:</td>
					<td><textarea style="resize:none" name ="gbPost" cols ="30" rows ="5" id ="gbPost" onKeyDown= "charRemaining(this.form.gbPost, this.form.charRem, 200)" onKeyUp= "charRemaining(this.form.gbPost, this.form.charRem, 200)"></textarea></td>
					<td><input readonly type = "text" name = "charRem" size = "3" maxlength = "3" value = "200"><br>Characters remaining<br></td>
				</tr>
				
				<tr>
					<td>Add to mailing list?</td>
					<td><input type = "checkbox" name = "add2mailer" value = "true" checked>
					<input type = "submit" value = "Submit"/></td>
                    
                    <script language="php"> $sql1 = "SELECT * FROM guestbookEntry";
									
					$result1 = mysql_query($sql1);


					while($row = mysql_fetch_array($result1)) 
					{
						echo '<div id="guestbookPost' + $row['postNo'] +'" class="guestbookHolder">';
						echo "<hr>";
						echo $row['timeStamp'];
						echo "<br />";
						echo $row['postNo'];
						echo "<br />";
						echo $row['name'];
						echo "<br />";
						echo $row['message'];
						echo "<br />";
                        echo "</div>";
					}
                    echo "</div>";
                    </script>
					
					<?php
		
					if($_POST){
						$timeStamp = date("y-m-d h:i:s");
						$isDeleted = "0";
						$name = "namefail";
						$eMail = "emailfail";
						$gbPost = "commentfail";
						$add2mailer = "0";
						
						if(isset($_POST["name"]))
						{
							$name = $_POST["name"];
						}
						
						if(isset($_POST["eMail"]))
						{
							$eMail = $_POST["eMail"];
						}
						
						if(isset($_POST["gbPost"]))
						{
							$gbPost = $_POST["gbPost"];
						}
						
						if(isset($_POST["add2mailer"]))
						{
							$add2mailer = (bool)$_POST["add2mailer"];
						}
						
						
						$sql = "INSERT INTO guestbookEntry(
							name,
							eMail,
							message, 
							timeStamp, 
							add2mailer,
							isDeleted) 
								VALUES (
									'$name',
									'$eMail',
									'$gbPost',
									'$timeStamp',
									'$add2mailer',
									'$isDeleted'
									)";
									
						$result = mysql_query($sql);
						
						if ($result)
						{
							echo "Success";
						}
						else
						{
							echo "Fail" . mysql_error();
						}
					}
					?>
					</div>
				</tr>
			</table>
		</form>
	</div>
	</body>
</html>

Is your professor ok with this?


$connection = @mysql_connect($host, $id, $pwd);

If he is, he gets docked credibility points for 1) allowing mysql* to be used rather than PDO and 2) ignoring errors from the connect (never use @ to ignore errors, its just bad practice)

Either way let’s just help you finish up. Now what “results” are you looking to display at the bottom of the page? What I would recommend is mocking up separate plain HTML files (with no PHP) with static test data to show how you want each page to look (before and after submission, including your mocked up “results”.

It’s the way she taught us to do it. So -2 credibility for teaching us that way…
http://1125804.studentwebserver.co.uk/clientweb/guestbook.php

See all the test data from the guestbook input? I want that at the bottom. Input on top, results on bottom.

Also, ignore the way it looks… I’m doing function before style…

Feel free to post to that by the way.

The first thing I notice is you have all your output in the same table as the form; in fact the output is in the form. I would start with a table for the form only and if you want a table for the output use a separate one; I do not tend to use <div> in a table and would either use a table or divs.

So firstly I would separate the form from the output.

Since we aren’t worried about format yet, I stripped the HTML.


<?php
//Check PHP is running
echo '<img src ="images/php.png" alt ="PHP is running" height="25px" width ="47px">';

//Establish a connection to the database
$host = "Mysql.studentwebserver.co.uk";
$id = "1125804_clientgb";
$pwd = "xxx"; //redacted
$db = "1125804_clientgb";
$tbl ="guestbookEntry";

$connection = @mysql_connect($host, $id, $pwd);

//test for connection, best practice is to use PDO so that we dont even have to deal with this portion (other than handling the exception if you want to)
if($connection) {
    echo '<img src ="images/serverSuccess.png" alt = "Connection to server successful" width ="26px" height ="25px">';
} else {
    echo '<img src ="images/serverFail.png" alt = "Connection to server unsuccessful" width ="26px" height ="25x">';
}

$dbconnect = @mysql_select_db($db);

//test for db, same as PDO comment above
if($dbconnect) {
    echo '<img src ="images/databaseSuccess.png" alt = "Connection to databse successful" width ="26px" height ="25px">';
} else {
    echo '<img src ="images/databaseFail.png" alt = "Connection to server unsuccessful" width ="26px" height ="25px">';
}

//form submitted, lets handle this before grabbing the entries so that the new one will show up on the same request
if($_POST){
    $timeStamp = date("y-m-d h:i:s");
    $isDeleted = "0";
    $name = "namefail";
    $eMail = "emailfail";
    $gbPost = "commentfail";
    $add2mailer = "0";

    if(isset($_POST["name"])) {
        $name = $_POST["name"];
    }

    if(isset($_POST["eMail"])) {
        $eMail = $_POST["eMail"];
    }

    if(isset($_POST["gbPost"]))    {
        $gbPost = $_POST["gbPost"];
    }

    if(isset($_POST["add2mailer"]))    {
        $add2mailer = (bool)$_POST["add2mailer"];
    }

    $sql = "INSERT INTO guestbookEntry(
        name,
        eMail,
        message, 
        timeStamp, 
        add2mailer,
        isDeleted) 
            VALUES (
                '$name',
                '$eMail',
                '$gbPost',
                '$timeStamp',
                '$add2mailer',
                '$isDeleted'
                )";
                
    $result = mysql_query($sql);

    if ($result) {
        echo "Success";
    } else {
        echo "Fail" . mysql_error();
    }
}

//moved this down below the post check so that new entries will show up on same request
$sql1 = "SELECT * FROM guestbookEntry"; //its generally frowned upon to use * (select all), try select  the columns you'll be using, even if it will be all of them                
$result1 = mysql_query($sql1);
while($row = mysql_fetch_array($result1)) {
    echo '<div id="guestbookPost' . $row['postNo'] . '" class="guestbookHolder"><hr>' .  "\
" . 
    $row['timeStamp'] . "<br />" .
    $row['postNo'] . "<br />" .
    $row['name'] . "<br />" . 
    $row['message'] . "<br />" . 
    "</div>";
}
//echo "</div>"; //why is this here? move to static html

Give this a test. Now, what "result are you trying to display at the end of the page rather than the beginning?

Side note, when you have a failure, (cant connect to db, you’ll want to exit cleanly without trying to run the other code. So keep that in that back of your mind for when your further along.

Ah yes, also throw your form at the top of the code I gave you. No need for the rest of the boiler plate to test this:


<form>...</form>
<?php
...

That actually fixed most of it. It’s now displaying after the form. Now I just need to move it down some. That’s easy enough

*Edit. Turns out it’s still just as broke. Just didn’t look it xD Trying your solution now Wolfe

That’s exactly what I want it to look like, but inside the way it was before. If that makes sense?
it even echoes out the div tags properly now =D

I’ve got this working and looking just how I want it thanks to you Wolfe, and you Rubble. Can I +rep you both on this?

Hey, sorry I wasn’t able to respond but I’m glad you got it working. No rep system here on SP :slight_smile:

Some things to take away:

  1. I recommend separating your HTML from your PHP as much as possible as I did for you, it makes things easier to read, debug, etc (one of the benefits of an MVC framework)
  2. Use PDO (maybe do it as a side project so that you don’t get in trouble by your professor for using something she didn’t teach) The mysql* extension is deprecated for many good reasons, PDO throws exceptions rather than errors, and it can handle sensitization for you (prevent sql injection, which your script right now is currently vulnerable to), and… Well I can go for days reallly
  3. Consider failures. How will your script act if it is unable to connect to the db, will it still try to run a query? You’ll want to find a clean way of preventing further execution.
  4. Even though your “handling” a potential error from not connecting, try to avoid suppressing errors with @ (for more food for though on errors, most certainly out of scope from your current lesson, and probably wont be taught, have a look a converting all of your errors and notices to exceptions, this will halt execution and allow for some catches and reporting done on them. https://github.com/KyleWolfe/PHPErrorNet)