PHP error displaying position. - php

I have following PHP code:
if($_SESSION['msg']['login-err'])
{
echo '<p class="error">'.$_SESSION['msg']['login-err'].'</p>';
unset($_SESSION['msg']['login-err']);
}
Everything working fine. 'P' with error is displayed correctly inside element.
My question is how to specify where my error should be displayed?
E.G. Not as the first element inside the form, but
as the second for example
just before <input name="user" />
??
Any suggestion much appreciated.

Since you're (somewhat naively) testing for errors and displaying errors at the same time, you should just move the code lower in the page so that the test/output happen where you want it to display.
Ideally you should decouple your display code from your logic. Store your errors for later display in an $errors variable which is passed to your template to be rendered.

Rather than placing the echo where it exist now, why not change your code to something like this:
$error;
if($_SESSION['msg']['login-err'])
{
$error = $_SESSION['msg']['login-err'];
unset($_SESSION['msg']['login-err']);
}
Then, right above your input tag, do something like this...
<?php echo $error;?>
It's not the best way to do error handling...but it should do what you are asking.

The "where" depends on you frontend design.
In a login form I would recommend to display errors at the top or bottom of the whole form. In a contact/registration form it makes more sense to show error beside the field ( on the top or left ).
Quite different thing is this combination of logic and presentations. They should be separated, because each piece of code should have only one reason to change. Your piece has two reasons: design or logic.
You would gain a lot if you did some extended studies in MVC and OOP in general.

Related

How to create a dynamic link?

I'm trying to create a link that takes the user to two different pages depending is the user logged or not. Problem is I'm still new to programming and this is quite big bite for beginner like me but its something I have to do. I created something like this so far but either way I suck at searching or there just isnt specific information for what I need
<?php if($userLogged){
echo '<a href="index.php" class="stylelink">';
}
else
{
echo '<a href="index1.php" class="stylelink">';
}
echo "Etusivu</a>";
?>
I'm also using Dreamweaver's login function that creates the MM_Username session and such, and Im not sure how to make the condition. userLogged is still an empty variable. Id appreciate any advice.
Thanks
-John
well, instead of using echo statements in the php tag you can write html and use php for outputting the value of the page like this
Etusivu
The $_SESSION['MM_Username'] works if you have included session_start(); at the beginning of the page and you can use the condition as above instead of $userLogged.

Is there a way to access previously created divs?

I'm creating divs with dynamic names using php such as:
echo "<div class=\"".$row['country']."\">"
So it's going to first create a series of divs such as ...
<div class="America">
//stuff goes in here
</div>
<div class="Germany">
//stuff goes in here
</div>
<div class="Singapore">
//stuff goes in here
</div>
But later on in the code after the "Germany" div has already been created, I'm going to make another mysql query to a different table and I want to access the "Germany" class and add content in it. It then becomes something like...
<div class="Germany">
<p> Germany has x number of people </p>
<p> The most popular car in Germany is x </p>
</div>
I know with Jquery there is the append() function. Is there something similar in PHP where I can access a div that's already been created and add stuff to it?
Note: all of this is in one php file that loads all the content when the page loads.
It can be done. You can use output buffering to capture all output. Then you can use an HTML DOM parser to modify that output. After that, you can flush the lot.
But this will work only once and it will seriously slow down your script. Don't do it, it smells of bad design.
Your best option would be to create multiple variables like
$css['America'];
$css['Germany'];
$general_output;
etc and, while you are building your site, just add info to the required variable.
Once you get to the end of the page, print them in the right order and you are done.
I think you can create an array like
$div["Amereica"] = "America"
And in future you can append value to this array. eg.
$div["Amereica"] .= 'text to append';
And finally you can use implode function or using other array functions you can crate final html.
If you really need to re-access that element, you're probably looking for DOM functions or phpQuery
Simple answer is no.
You can't change HTML code produced by PHP, because that code is already sent to browser, and PHP works on server side.
One of complicated answers is #GolezTrol answer.

Codeigniter PHP - loading a view at an anchor point

I have a form at the bottom of a long page, if a user fills out the form but it doesn't validate the page is reloaded in the typical codeigniter fashion:
$this->load->view('template',$data);
however because the form is way down at the bottom of the page I need the page to load down there like you do with HTML anchors. Does anyone know how to do this in codeigniter?
I can't use the codeigniter
redirect();
function because it loses the object and the validation errors are gone. Other frameworks I've used like Yii you can call the redirect function like:
$this->redirect();
which solves the problem because you keep the object. I've tried using:
$this->index()
within the controller which works fine as a redirect but the validation errors are in another method which is where the current page is loaded from:
$this->item($labs)
but when I use this it get stuck in a loop
Any ideas? I've seen this question a lot on the net but no clear answers. I'm researching using codeigniter "flash data" but think it's a bit overkill.
cheers.
I can't personally vouch for this, but according to this thread if you append the anchor to the form's action, it will work.
CodeIgniter helper:
<?php echo form_open('controller/function#anchor'); ?>
Or vanilla HTML:
<form method='post' action='controller/function#anchor'>
If you were open to using Javascript, you could easily detect a $validation_failed variable and appropriately scroll. Or, even better, use AJAX.
Another option is to put the form near the top of the page?
Ok, as far as I understood your problem, it isn't much related to the back end(codeigniter). You want the form at the bottom of the page to be 'what-users-sees-on-page-load' (since you mention anchors).
Now, what you can do is, you can set delimiters for your validation error messages using:
echo validation_errors('<div id="bottom_form_error">', '</div>');
Using jQuery ScrollTo, do:
$( function() { $('#bottom_form_error').ScrollTo(); } );
And, the user will be scrolled to the errors at the bottom of the page. Don't forget to include jQuery too.
Anchor hash fragment click is different - it is scrolling at ∞ speed.
I hope that is what you wanted.
P.S. I am ignoring what you said below this line:
Does anyone know how to do this in codeigniter?
as I felt it is not really relevant to the question.

Is it better to implement a FORM and its ACTION with a single PHP file or two files?

I'm creating a FORM with PHP for an intranet webpage. Another PHP script is called by submitting the form.
Before anyone asks, the form does not allow any uploads, and although the values entered in the form find their way into an SQL query, I strip out everything but numbers.
I'm wondering if there would be a advantage in using the same PHP file for both the FORM and the ACTION?
Obviously, increased complexity is the penalty — ie, figuring out, when invoked, if the FORM is to be created, or if the SUBMIT button has been clicked — but what would be the benefits?
EDIT: Note, the PHP in 'submit' mode does not redisplay the form, it does something entirely different. This is the source of the complexity I was worried about.
The form is used to enter values which are checked against values in a DB, but there are no changes made to the DB.
I tend to find it more maintainable to have the php that creates the form separate from the php that is called by the form.
It will also reduce (though it isn't noticeable) one if statement to determine if this is a form request or filling in the form.
But, the problem is that unless you are going to take them to a new page, you will have to get the values back into the form which can be more complicated.
So, if you want to keep the values in the form, even after the form is processed, then leave the form processing logic at the beginning of the file, otherwise I would opt for maintainability and have them in two files.
In most case, I prefer that.
Keeping both together make the code more 'cohesive' as the code of accepting value (via form) is in the same php file (called it View and Control). To me this is an advantage.
However, the code that manipulate database should be separated in other file as it not the same as accepting value (called it a model library). This make it less-coupling as accepting and manipulation is separated. This decoupling will reduce the complexity you are worrying about.
Another advantage of is the URL. The users will see it as from the same page.
However, this is totally depends on your overall system metaphor and work flow. For example, it make better sense to the users that addBook.php handle book adding form and show that the adding has success or fail. Comparing that too having two addBook.php, addBookProcess.php.
What I am trying to say is that the flow of pages should be a more important factor to determine if you want to separate or combine them. Decoupling interface/logic code will helps you reduce the complexity if pages need to be combine into one php file.
Just my though.
Form is about user interface, action is about doing something with data.
The part of code that actually processes user input must certainly be separate from the form structure.
The form code must accept default values (or values previously entered and found to be invalid), error messages etc. It must have nothing to do with usage of successfully submitted form data.
If you allow user to change invalidated input, then you must have action URL the same as form.
If successful submission leads to something unrelated, then its URL must be different from that of the form. Basically, you must redirect user from the URL where the form got accepted to the next URL.
If you're doing AJAX, none of this applies.
It depends!
The upside to having them in one file is that it puts a single block of functionality into one place and allows you to handle form validation. The downside is increased complexity. It really starts to suck if you have the markup for both pages in one file.
I would suggest having 3 files - the main PHP handler, the template for the form and the template for the result page. The main PHP file would look something like this:
<?php
$error_message = "";
if ($form_submitted){
if ($form_validated){
include("inc-result.txt");
exit;
}else{
$error_message = "something went wrong!";
}
}
include("inc-form.txt");
?>
if validation fails, the logic drops you back to the form, where you can display the previously entered values, along with the relevant error message.
it does depend but in the long-term I would suggest separation of forms and business logic.
For quick projects I do understand the short-term gain of keeping it in the same page but you never know when the form you did needs to be added with features or needs to be turned to an ajax form. If you keep your logic separate from the form you would be ready for these changes quicker.
Well, mainly if you want to re-show the form to the users without losing data, then you can just write something like this:
<input type="text" name="myInput" value="<?php
echo htmlspecialchars(isset($_POST["myInput"]) ? $_POST["myInput"] : "");
?>">
Update: here is an example of this method:
<?php
$error = "";
$result = "";
$a = isset($_POST["a"]) ? $_POST["a"] : "";
$b = isset($_POST["b"]) ? $_POST["b"] : "";
if ($a !== "" && $b !== ""){
if (is_numeric($a) && is_numeric($b))
$result = sprintf("%s + %s = %s", $a, $b, $a + $b);
else
$error = "You must enter two numbers!";
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head><title>Sum numbers</title></head>
<body><form method="post" action="<?php print htmlentities($_SERVER["REQUEST_URI"]); ?>">
<p><strong>Enter two numbers to add them together.</strong></p>
<?php if ($error){ printf ("<p><em>%s</em></p>", htmlspecialchars($error)); } ?>
<p>
<input type="text" name="a" value="<?php print htmlspecialchars($a); ?>">
+
<input type="text" name="b" value="<?php print htmlspecialchars($b); ?>">
<input type="submit">
</p>
<?php if ($result){ printf("<p><strong>%s</strong></p>", htmlspecialchars($result)); } ?>
</form></body>
</html>
It seems like you should do 2 things:
1) create controller that steps in to see if you are doing an edit action or a display action
you already have the start of one at the top of your file there, just make it include "form.php" (your form) after it does it's business. So yes, make 2 files.
2) pull all that crappy formatting code up into the controller. Calculate all your values before the form is ever loaded. This includes running htmlspecialchars on all your form elements that need it. You can even loop through them to save lines of code:
i.e.
$cleanTheseVars = array ($a, $b, $c $error, $result);
array_walk($cleanTheseVars, 'htmlspecialchars' );

PHP and HTML integration

I have a php file that contains a HTML form, then PHP logic, then an HTML footer...in that order.
I am trying to get the values from the form into some php validation logic in the botton of the page (but before the footer) using <?php VALIDATION LOGIC HERE ?>.
the problem is when the validation finds an error, the php logic will die() and hence, my HTML footer will not be executed.
is there a way to get my HTML footer to execute despite my php die();? ...or is there a better overall way to integrate my HTML and PHP? Thanks! Anyhelp would be much appreciated.
EDIT:
I actually have die() almost everywhere in my code where I am about to connect to a database. If the user credentials are correct, they connect..if credentials are wrong then it will die()..
Is this good practice and use of die()? it seems the solution to my problem is to use return() INSTEAD OF die()...in order to continue processing the HTML footer.
Also, I have situations such as mysql_connect() or die(). How can i would continue processing the remaining HTML page when die() is executed before the HTML is processed? ..i don't think mysql_connect() or return; is good practice right?
Thanks so much again in advance! The feedback has been very helpful!
As other states, you should have multiple files; header.php, index.php, footer.php, formvalidator.php.
In your index.php file, you should include header.php and footer.php.
In the form tag, action is sett to load formvalidator.php
In the form validator script, you could have something like this:
// All form fields are identified by '[id]_[name]', where 'id' is the
// identifier of the form type.
// The field identifier we want to return is just the name and not the id.
public function getFormData() {
$formData = array();
foreach ($_POST as $key => $value)
{
// Remove [id]_
$name = preg_replace('!.*_!', '', $key);
if (is_array($value)) {
$formData[$name] = implode(',', $value);
} else {
$formData[$name] = $value;
}
}
return $formData;
}
Now you can loop through the array and validate each field.
If you find an error, echo an error message, otherwise process the form.
Update
Answer to your update.
You should "never" use die(). Instead, exit thefunction you are in and return an error message. If you simply die(), you never know what went wrong where.
It is not possible to do server validation of a form unless you click the submit button.
You can put the code I gave you in the same PHP file as the form, and when you submit, you simply reload the same page (just set action="<?= $_SERVER['PHP_SELF'] ?>")
If you want to validate fields before submit, you must to this using javascript, like e.g. jQuery.validate.
Hmm... seem like you need some more knowledge of how to mix PHP with HTML.
Take a look at this beginners guide on how to work with forms in PHP.
I would use an external file for form processing and validation, then redirect back to the form page on error/success, displaying an error/success message.
I just make one header.php and one footer.php file. If there is an error just return instead of die.
This way at the top of your page you can just put:
<?php include('header.php');?>
///put in whatever html there may be
<?php
/// put your form and processing info here
///just return if you need to prevent further processing
?>
///put in whatever html there may be
<?php include('footer.php');?>
there are many better ways to do what you are doing. but to answer your first question, you can create a function called footer that returns a string with html needed to be displayed in the footer and call the die(footer()); but... why do you use die ? can't you just count the errors and display them somewhere in the result ? you should not kill the script that way.
And for the second question. you can use as BenTheDesigner said, a html page with the form action pointing to a php script that validates and either returns to the form if something went wrong or go somewhere else if not. but there too, you should remove the die() function and call something else to redirect you. you can use a template system like smarty to separate your logic from your html presentation. you can write it all in a single file but try to write you're entire logic at the top of the file and all the html at the bottom. and use <?=$var?> to display php stuff, or simple conditionals for diferent html results. but don't use die(). it just complicate things I guess.
Using die() is not a good practice because it will not show a friendly message to the user visiting your site. You should be absolute sure you want to use die. For example, you may use it in procedures when you suspect there is a hacking attempt. Instead try to use if else structure to show or hide things. Here is the possible prototype that you may want to implement:
// if there is a validation error, show it, otherwise not
if ($error == true)
{
// show footer
}
<!-- Your footer goes normally here -->

Categories