need help with html and php
Go to solution
Solved by mariushm,
You can mix html code and php code in a single file, with the PHP extension.
Fragments of php code must be between <?php and ?>
You don't generally want to escape the content received from the user as soon as you get it, instead only escape it when you're about to print it on page.
If you escape it like you do, then the text will be saved into the database escaped and later, someone may retrieve the text from database a second time and escape it again.
I like to have the variables initialized with some empty or default value, so that they will exist later in the page even if user didn't post
<?php $submit = false; $submit_valid = false; $submit_errors = ""; $Title= ""; $Indhold = ""; $Uid = 0; // needed by add_post - figure it out what's that about IF ($_SERVER['REQUEST_METHOD']=='POST') { $submit = true; // keep track in a variable if data was submitted or not, for later $Title = $_POST['title']; // input name = "title" $Indhold = $_POST['content']; // input name="content" $Uid = $_POST['uid']; // if needed // optional validation of input, let's say we don't want to submit empty text boxes (or boxes that only have spaces) $submit_valid = true; // assume data is valid, now check it if (trim($Title)=='') { $submit_valid = false; $submit_errors .= 'Type a title.';} if (trim($Indhold)=='') { $submit_valid = false; $submit_errors .= 'Type a content.';} if ($submit_valid == true) { // add the content to the database add_post($Uid,$Title,$Indhold); // up to you if you want to clear the Title and Indhold variables. } } /* best not to have empty lines or spaces before <html> */ ?><html> <head><title></title></head> <body> <h1> Opret Indlæg</h1> <?php // if there was a post, we could either say message arrived, or failure and failure reason if ($submit==true) { if ($submit_valid==true) { echo '<p>Thank you. Message received and added to database.</p>'; } else { echo '<p>Sorry, there was at least one problem submitting your post : '.$submit_errors.'</p>'; } } ?> <main> <form action="opret_rediger.php" method="post"> <label for="title">Titel:</label> <input type="text" name="title" id="title" required value="<?php echo htmlspecialchars($Title); ?>" > <label for "content">Indhold:</label> <textarea name="content" id="content" rows="4" cols="50" required ><?php echo htmlspecialchars($Indhold); ?></textarea> <?php /*optional if you need to send that Uid with title and content */ ?> <input type="hidden" name="uid" value="<?php echo htmlspecialchars($Uid);?>"> <button type="submit">Submit</button> </form> </main> </body> </html>
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now