In a Profile page of the User, I want to validate his input with PHP after submission and display errors on the same page before updating in the database.
For this, I'm doing something like:
<div>
<?php
if (isset($_POST["submitted"])) {
if (!isValidEmail($_POST["email"])) {
echo "<p>Please enter a valid email address.</p>";
return; // or exit;
}
if (!isValidPhoneNumber($_POST["phoneNumber"])) {
echo "<p>Please enter a valid phone number.</p>";
return; // or exit;
}
...
if (updateUser($id, $email, $phoneNumber, $name)) {
echo("<meta http-equiv='refresh' content='0'>");
} else {
echo "<p>An error occurred! Could not update your profile information!</p>";
}
}
?>
</div>
<my-footer></my-footer>
So when an error occurs upon PHP validation, the footer doesn't appear. So I understood that with return or exit the page will stop rendering at that command.
What can I do to solve this issue?
I want it to stop execution of the PHP script but display the rest of the HTML page.
You could put your validation logic inside a function at the top of your page, and change all your echo to return.
function validate() {
if (isset($_POST["submitted"])) {
if (!isValidEmail($_POST["email"])) {
return "<p>Please enter a valid email address.</p>";
}
if (!isValidPhoneNumber($_POST["phoneNumber"])) {
return "<p>Please enter a valid phone number.</p>";
}
//...
if (updateUser($id, $email, $phoneNumber, $name)) {
return "<meta http-equiv='refresh' content='0'>";
} else {
return "<p>An error occurred! Could not update your profile information!</p>";
}
}
}
Then simply echo the string returned from the function above the footer.
<div>
<?php echo validate(); ?>
</div>
<my-footer></my-footer>
Note that the above will work because $_POST is a superglobal. However, you may consider changing your function to pass email, phoneNumber, name and id as parameters instead.
Change your flow up a little bit...
if (isset($_POST["submitted"])) {
$has_errors = FALSE;
$err_msg = '';
if (!isValidEmail($_POST["email"])) {
$err_msg .= "<p>Please enter a valid email address.</p>";
$has_errors = TRUE;
}
if (!isValidPhoneNumber($_POST["phoneNumber"])) {
$err_msg .= "<p>Please enter a valid phone number.</p>";
$has_errors = TRUE;
}
if ( $has_errors ) {
echo "<p>Please Correct the following and resubmit...</p>" . $err_msg;
} else {
if (updateUser($id, $email, $phoneNumber, $name)) {
echo("<meta http-equiv='refresh' content='0'>");
} else {
echo "<p>An error occurred! Could not update your profile information!</p>";
}
}
}
Many times you will see PHP frameworks that can handle this for you.
Here's a good website to compare a few: http://phpframeworks.com/
But what you can do is put your footer (and / or the rest of your code) into a function that holds the rest of your code for you, and you can call it later or whenever you need to so you can still end code execution gracefully.
<div>
<?php
function footer() {
$string = "</div>";
$string .= "<my-footer></my-footer>";
return $string;
}
if (isset($_POST["submitted"])) {
if (!isValidEmail($_POST["email"])) {
echo "<p>Please enter a valid email address.</p>";
die(footer()); // Displays footer
}
if (!isValidPhoneNumber($_POST["phoneNumber"])) {
echo "<p>Please enter a valid phone number.</p>";
die(footer()); // Displays footer
}
...
if (updateUser($id, $email, $phoneNumber, $name)) {
echo("<meta http-equiv='refresh' content='0'>");
} else {
die("<p>An error occurred! Could not update your profile information!</p>" . footer()); // kills the page execution, but still returns the foot of the page.
}
}
echo footer();
?>
Related
I'm working on an e-commerce website project, and I'm trying to validate customer's information using PHP. And I'm here trying to check if the customer put his/her phone number, and to check if the phone number is in the correct form. So first, I check the POST array if it's empty or not, if it is empty, I show an error message "Phone number must be entered". And if there is a phone number, I check the REGEX and if it does not match, I show an error message "Phone number is invalid". And everything is correct, just proceeds. But somehow, below my code, does not check REGEX. If it is empty, it shows an error message for the empty field, but not REGEX. Why is this so?
if (!empty($_POST)) {
$error = false;
if (empty($_POST["phone"])) {
echo "<p class='errorMessage'> Phone must be entered. </p>";
$error = true;
}
if (!empty($_POST["phone"])) {
if (!preg_match("/^[2-9]\d{2}-\d{3}-\d{4}$/", $_POST['phone'])) {
echo "<p class='errMessage'>Phone number is invalid</p>";
}
}
if (!$error) {
header("Location: confirmation.php");
exit;
}
}
And here is the HTML part:
<tr>
<th><label for="phone">Phone Number</label></th>
<td><input class="inputField" type="text" id="phone" name="phone"
<?php
if (isset($_POST["phone"])) echo "value='" . $_POST["phone"] . "'";
?>></td>
</tr>
This is because you don't declare error if the regex is invalid, so the code proceeds :
if (!empty($_POST)) {
$error = false;
if (empty($_POST["phone"])) {
echo "<p class='errorMessage'> Phone must be entered. </p>";
$error = true;
}
if (!empty($_POST["phone"])) {
if (!preg_match("/^[2-9]\d{2}-\d{3}-\d{4}$/", $_POST['phone'])) {
$error = true;
echo "<p class='errMessage'>Phone number is invalid</p>";
}
}
if (!$error) {
header("Location: confirmation.php");
exit;
}
}
Try the following code:
if (strlen($_POST["phone"]) >0) {
if (!preg_match("/^[2-9]\d{2}-\d{3}-\d{4}$/", $_POST['phone'])) {
$error = true;
echo "<p class='errMessage'>Phone number is invalid</p>";
}
else {
echo "<p class='errorMessage'> Phone must be entered. </p>";
$error = true;
}
Hi guys so im creating this registration page for my website in php..This is the PHP script
# Script 9.5 - register.php #2
// This script performs an INSERT query to add a record to the users table.
$page_title = 'Register';
include ('includes/header.html');
// Check for form submission:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$errors = array(); // Initialize an error array.
// Check for a name:
if (empty($_POST['name'])) {
$errors[] = 'You forgot to enter your name.';
} else {
$n = mysqli_real_escape_string($dbh, trim($_POST['name']));
}
// Check for an email:
if (empty($_POST['email'])) {
$errors[] = 'You forgot to enter your email.';
} else {
$e = mysqli_real_escape_string($dbh, trim($_POST['email']));
}
// Check for a password and match against the confirmed password:
if (!empty($_POST['pass1'])) {
if ($_POST['pass1'] != $_POST['pass2']) {
$errors[] = 'Your password did not match the confirmed password.';
} else {
$p = mysqli_real_escape_string($dbh, trim($_POST['pass1']));
}
} else {
$errors[] = 'You forgot to enter your password.';
}
// Check for contact number:
if (empty($_POST['contact_no'])) {
$errors[] = 'You forgot to enter your contact no.';
} else {
$cn = mysqli_real_escape_string($dbh, trim($_POST['contact_no']));
}
if (empty($errors)) { // If everything's OK.
require 'connect_db.php';
$conn= mysqli_connect('*****' , '*****', '*****' , '*****' ,****);
// Make the query:
$q = ("INSERT INTO register_user(name, email, pass, contact_no) VALUES ('$n', '$e','$p','$cn')");
$r = #mysqli_query ($dbh, $q);// Run the query.
if ($r) { // If it ran OK.
// Print a message:
echo '<h1>Thank you!</h1>
<p>You are now registered. </p>
<p>Login </p>';
} else { // If it did not run OK.
// Public message:
echo '<h1>System Error</h1>
<p class="error">You could not be registered due to a system error. We apologize for any inconvenience.</p>';
// Debugging message:
echo '<p>' . mysqli_error($dbh) . '<br/><br/> Query: ' . $q . '</p>';
} // End of if ($r) IF.
mysqli_close($dbh); // Close the database connection.
// Include the footer and quit the script:
include ('includes/footer.html');
exit();
} else { // Report the errors.
echo '<h1>Error!</h1>
<p class="error">The following error(s) occurred:<br>';
foreach ($errors as $msg) { // Print each error.
echo " - $msg<br>";
}
echo 'Please try again.</p>';
} // End of if (empty($errors)) IF.
mysqli_close($dbh); // Close the database connection.
But the thing is once i register this is the output:
System Error
You could not be registered due to a system error. We apologize for any inconvenience.
Query: INSERT INTO register_user(name, email, pass, contact_no) VALUES ('', '','','')
so im kindly would glad for any assistance
You're calling mysqli_real_escape_string() BEFORE you establish your DB connection. This is not permitted. You MUST have a connection before doing the escape operations.
That means every single one of your form fields is going to be a boolean FALSE value, which signifies failure.
Your code should be structured
1. connect to db
2. process form inputs
3. if form inputs ok, insert into db
You've got #1 and #2 reversed.
Model
$q = $this->db->get_where('person', array('p_id' => $p));
if($q->num_rows()!=1)
{
redirect('General_Area/Home');
exit();
}
else
{
. . .
Ok So once the model is initialized it queries the db and looks for exactly one match and if found it moves on the else statement. However if not found it will redirect('General_Area/Home');
How do I pass a message in there? In my controller I am returning an object if the query is successful.
And in my view i am echo obj->table_col_name
$q = $this->db->get_where('person', array('p_id' => $p));
if($q->num_rows()!=1)
{
return $Error = 'You have not been found!...';
#redirect('General_Area/Home');
exit();
}
else
{
. . .
If the $q was not successful I want to be able to echo $error; in the view for the user to see the message.
In your Model
if($q->num_rows()>0)
{
return array('result'=>$q->result(), 'message'=>'This is a message');
}
return false;
In the Controller
$this->load->model('your_model_name');
$data['query']=$this->your_model_name->model_function_name();
if(!$data['query']['result'])
{
redirect('General_Area/Home');
exit();
}
else $this->load->view('your_view_name',$data);
In your View
if(isset($query))
{
foreach($query as $row)
{
// code goes here to echo columns
}
//and message is available as $message so you can print it like
if(isset($message)) echo $message;
}
Message on redirect
Also if you want to send a message when you redirect to another page you can use in your controller
if(!$data['query']['result'])
{
$this->session->set_flashdata('message', 'your message text here!');
redirect('General_Area/Home');
exit();
}
So you can print the message in the view like
echo $this->session->flashdata('message');
Read more about Flashdata.
<?php
if (isset($_POST['ign'], $_POST['email'])) {
if($_POST['ign'] && $_POST['email']){
}
else {
echo ("Please enter all of the values!");
}
}
else {
echo ("Error in form data!");
}
if((FILTER_VALIDATE_EMAIL($_POST['email'] == TRUE))) {
$email = $_POST['email'];
echo ("Thanks, " . htmlentities($_POST['ign']) . ", you will recieve an email when the site is complete!");
}
else {
echo "Failure!";
}
// insert email and ign into database
?>
Is this going to work correctly? First time doing something completely from scratch lol!
OK! I have changed it. What about this? Should I also do the empty thing?
<?php
if (!isset($_POST['ign'], $_POST['email'])) {
if($_POST['ign'] && $_POST['email']){
echo "Please fill out all of the fields!";
die;
}
if(var_filter($_POST['email'], FILTER_VALIDATE_EMAIL))
$email = $_POST['email'];
echo ("Thanks, " . htmlentities($_POST['ign']) . ", you will recieve an email when the site is complete!");
}
else {
echo "Your email was invalid!";
}
// insert email and ign into database
?>
Use built in functions, don't re-invent the wheel:
if(filter_var($mail, FILTER_VALIDATE_EMAIL)){
echo "Mail is valid!";
}
WHY IS YOUR FUNCTION NAME ALL CAPS?
...and do you see the difference between this...
if(func($_POST['email'] == TRUE)){
and this..
if(func($_POST['email']) == TRUE){
?
There are lots of mistakes there. Here's what you should be doing:
// First check if both fields are present. Usually there is no point in doing this
// because the next check will also catch this case, but you had it so I put it in too.
if (!isset($_POST['ign'], $_POST['email'])) {
echo ("Error in form data!");
die; // or something else
}
// Then check if both values are non-"empty" (you might want to look at the docs for
// an explanation of what this means exactly).
if (empty($_POST['ign']) || empty($_POST['email'])) {
echo ("Please enter all of the values!");
die; // or something else
}
// Finally, validate the email. DO NOT COMPARE WITH true!
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
echo "Failure!";
die; // etc
}
echo ("Thanks, " . htmlentities($_POST['ign']) . ", blah blah!");
How do I get this to not display when you first go to the page???
if ($error) {
echo "Error: $error<br/>";
}
if ($keycode) {
echo "Keycode: $keycode<br/>";
}
<?php
session_start();
if ($_SESSION['been_here'] == true) {
// show what you need to show
}
else {
// don't show it
$_SESSION['been_here'] = true;
}
?>
The point here is that $_SESSION-variables "last" (as long as you session_start()).
Google "php sessions" for more information, and ask more questions on SO if necessary. :)
Use session_destroy(); to destroy the session.
<?php
if ($error){ echo "Error: $error
"; } if ($keycode) { echo "Keycode: $keycode
"; }
Based on the comments, it seems that your conditional is evaluating to true before you expect it to. Without seeing more of your code, this is only a guess, but I believe your problem is that you're giving the variable $error a default/temporary value when you create it that doesn't mean false. For example:
$error = "default error message, change me later";
// Later...
if ($error) { // This evaluates to true
echo "Error: $error<br/>";
}
If so, you'll want to check out PHP's documentation on casting to booleans, and maybe use something like this (with contribution from Christian's answer):
$error = "0"; // Default error message, change it later
// Later...
if($_SESSION['been_here'] == true)
$error = "This is the real error message.";
// Even later...
if ($error) {
echo "Error: $error<br/>";
}
This probably works for you:
if (isset($error) && !empty($error)) {
echo "Error: $error<br/>";
}
I cannot say more, because you have not specified what the value of $error might be.
Or you just have to introduce a flag that indicates that an error occurred:
$error = 'Error message.';
$has_error = false;
if(!empty($_POST) && some_condition) { // means it is a POST request
$has_error = true;
}
if($has_error) {
echo "Error: $error<br/>";
}