Page 1 of 1

Newbie - Code Optimization

Posted: Wed Aug 30, 2006 10:02 am
by tmaiden
I have a html document, register.html, which has a form on it. The form calls register.php to insert the form values into my database.

When register.php finds an error, user input, it is displayed and the user is shown the form again.

I don't like how I am doing this and wanted to know if anyone has any suggestions on how to optimize this.

Code: Select all

<?php

	include('config.php');

	//Connect to database

	if(user input is wrong){
		$errormessage = $errormessage . "You did this wrong.<br>";
	}

	if(!(is_null($errormessage)))
	{
?>
<html>
	<body>
	...
	<p>
<?
    	echo $errormessage; 
?>
	</p>
	<form>
		<!-- TEXT BOXES AND STUFF -->
	</form>
	</body>
</html>
<?
    	exit();
	}
	$query = "INSERT FORM VALUES INTO TABLE";
	mysql_query($query) or die(mysql_error());
	mysql_close();
?>
<html>
	<body>
	...
	<p>
    	    	THANK YOU FOR REGISTERING 
	</p>
	<!-- No form needed, since registration was successful -->
	</body>
</html>
If you don't understand the code; I'll be more then glad to elaberate.

THANKS!

Posted: Wed Aug 30, 2006 10:52 am
by nincha
not much to optimize

Posted: Wed Aug 30, 2006 11:16 am
by tmaiden
Lines 14-17 and 34-37 are the same; is that worth putting in a function or something?

Code: Select all

1<?php
2
3	include('config.php');
4
5	//Connect to database
6
7	if(user input is wrong){
8		$errormessage = $errormessage . "You did this wrong.<br>";
9	}
10
11	if(!(is_null($errormessage)))
12	{
13?>
14<html>
15	<body>
16	...
17	<p>
18<?
19    	echo $errormessage; 
20?>
21	</p>
22	<form>
23		<!-- TEXT BOXES AND STUFF -->
24	</form>
25	</body>
26</html>
27<?
28    	exit();
29	}
30	$query = "INSERT FORM VALUES INTO TABLE";
31	mysql_query($query) or die(mysql_error());
32	mysql_close();
33?>
34<html>
35	<body>
36	...
37	<p>
38    	    	THANK YOU FOR REGISTERING 
39	</p>
40	<!-- No form needed, since registration was successful -->
41	</body>
42</html>

Posted: Wed Aug 30, 2006 12:59 pm
by yonta
You could use a template system, like Smartyor Savant- which would allow you to separate the php from the html (php in php files, html in template files).

And the repeated lines could go in a header template.

Otherwise you could, like you suggested, build a separate function

function display_header() { echo 'whatever'; }

Or simply echo those lines (around line 5) before you check if the input is valid or not (since they're going to be printed out anyway).