I am writing a small data entry form. Data gets entered in html form by user & then into csv file on server. Consider the following snippet, that i wrote to do this
if(!empty($_POST)) {
$handler = fopen('database.csv','a') or exit("Error: Unable to open file!");
fputcsv($handler,$_POST);
fclose($handler);
}
?>
Pretty simple!
The only "fancy" task is display a message to confirm that the entry has been added to the database(Entry added), clearing the form ready for the next entry. Or incase of error, display error message(Doh! Write failed ). I can use OR statement but that would only be invoked incase of an error.
Any idea how to do this?
[UPdate]
Thanks for excellent replies everyone! I added conditional statement as everyone suggested
if(!empty($_POST)) {
$handler = fopen('database.csv','a') or exit("Error: Unable to open file!");
if(fputcsv($handler,$_POST)) {
echo 'everything okay, add next record';
}
else {
exit('Error: Record add failed. Try again or contact admin');
}
fclose($handler);
}
if(!empty($_POST)) {
$handler = fopen('database.csv','a');
if ($handler === FALSE) {
exit("Error: Unable to open file!");
} else {
fputcsv($handler,$_POST);
fclose($handler);
echo "everything A-ok";
}
}
You can include a 3-state switch that:
) does data entry and re-displays the cleared form;
) displays the error and re-populates the form so user can fix it;
) default to no data entry, clear form
Use a post or session variable to specify the action to take, default to no action if the variable is not set or does not validate.
Related
I want to show an error on the same as page as my form. My form is going to another page and then processing and returning the result. How can I show the error on the previous page?
if($_POST['btnManage']=="Signup"){
$objCustomer->Email=$_POST['txtEmail'];
$objCustomer->Password=$_POST['txtPassword'];
$Status=$objCustomer->Signup();
if($Status>0)
{
session_start();
$_SESSION['Email']=$objCustomer->Email;
header("Location:../index.php");
} else
{
echo "error";
}
}
Going with what you have using $_SESSION, you can set eorr in the session.
else
{
$_SESSION["eorr"] = "message_here";
header("Location:../{form_page_here}");
}
Then on the page that has your form, do a check if $_SESSION["eorr"] is set an display the message. You would also need to unset($_SESSION["eorr"]; after it is displayed so it is removed if you do not need to use it again.
Three step to handle the error
step1: define your error code and error message
define('SYSTEM_ERROR',1000);
define('SYSTEM_ERROR_MESSAGE','your error message');
step2: put the current error code to the reference url as a parameter
http://localhost?error=1000
step3: redirect to the reference page ,handle the error code and show to the page
$error = $_GET['error'];
if($error ==SYSTEM_ERROR){
$errorMessage = SYSTEM_ERROR_MESSAGE;
}
//show the $errorMessage
I'm experiencing a very odd problem. Everything works as expected on my local host. When I upload to a live server, the page just cuts off right where I'm including a file. Just white space beneath it. Nada...
The line that breaks is:
<? require_once('inc/store-address.php'); if($_GET['submit']){ echo storeAddress(); } ?>
And the file being included is:
<?php
/*///////////////////////////////////////////////////////////////////////
Part of the code from the book
Building Findable Websites: Web Standards, SEO, and Beyond
by Aarron Walter (aarron#buildingfindablewebsites.com)
http://buildingfindablewebsites.com
Distrbuted under Creative Commons license
http://creativecommons.org/licenses/by-sa/3.0/us/
///////////////////////////////////////////////////////////////////////*/
function storeAddress(){
// Validation
if(!$_GET['email']){ return "No email address provided"; }
if(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*$/i", $_GET['email'])) {
return "Email address is invalid";
}
require_once('MCAPI.class.php');
// grab an API Key from http://admin.mailchimp.com/account/api/
$api = new MCAPI('xxxxxxx');
// grab your List's Unique Id by going to http://admin.mailchimp.com/lists/
// Click the "settings" link for the list - the Unique Id is at the bottom of that page.
$list_id = "xxxxxx";
if($api->listSubscribe($list_id, $_GET['email']) === true) {
// It worked!
// return 'Success! Thank You!';
echo '<script> window.location.href = "thank-you.php"; </script>';
}
else
{
// An error ocurred, return error message
return 'Error: ' . $api->errorMessage;
}
}
// If being called via ajax, autorun the function
if($_GET['ajax']){ echo storeAddress(); }
?>
The only thing edited in the above code is the API key and List ID.
its because is missing parentesis on your if condition.
require_once('inc/store-address.php');
if($_GET['submit'] **)** {
echo storeAddress();
}
It seems there was an error. It was working on my local server because there wasn't an error.
I was using filezilla do upload my content. For some reason it appears to be an encoding issue when uploading.
I don't know if I should delete this question or answer to help someone else with the problem later on so I chose the later.
I manually uploaded my file and guess what, it works!
I am working with a from in codeigniter where program control is moving to submit function which I can test by adding the die function. Although set_rules() are successfully checking the entry but the control is not being passed to if($this->form_validation->run()) this function. Its getting out of it and running the die function dead-2 that I have kept to test the program flow.
Below is my controller code
function addPost(){
$this->load->library('form_validation')
if($this->admin_lib->checkMembers()){
if($this->input->post('submit')){
//validate the form
$this->form_validation->set_rules('country','Country','required');
$this->form_validation->set_rules('city','City','required');
$this->form_validation->set_rules('area','Area','required');
$this->form_validation->set_rules('street','Street','required');
$this->form_validation->set_rules('house_no','House number','required|numeric');
if($this->form_validation->run()){
//add to database
die("dead-1");
if($this->members_model->addPost())
{
echo "Successfully made one entry will be validated";
}
else{
echo "Error uploading the datas into database Please contact us about the problem";
}
}
die("Dead -2");
}
$data['content']=$this->load->view('members/addPost','',true);
$this->load->view('members/home',$data);
}
else{
echo "you dont have preveledge to access this page ,<br/> LOgin link rakhnu paryo ";
}
}
Your code will always call die("Dead -2") because it isn't part of an Else block. It's sitting directly below your If statement which means, regardless of what happens with your form validation, it will always die.
Consider changing your code to the following
if($this->form_validation->run())
{
//add to database
die("dead-1");
if($this->members_model->addPost())
{
echo "Successfully made one entry will be validated";
}
else
{
echo "Error uploading the datas into database Please contact us about the problem";
}
}
else
{
die("Dead -2");
}
I want to check if 'dbas.php' is included in 'ad.php'. I wrote the code -
ad.php
<?php if(file_exists("dbas.php") && include("dbas.php")){
// some code will be here
}
else{echo"Database loading failed";}
?>
I successfully tested the file_exists() part but don't know if the include() will work well or not, cause I tried in localhost and if the file is in directory then it never fails to include. So I don't know how this code would behave in the server if much traffic be there. So please tell me is my code correct ?
-Thanks.
Solved: Thank you so much for your answers.
Using php's require method is more suitable if you want to be absolutely sure that the file is included. file_exists only checks if the file exists, not if it's actually readable.
require will produce an error if inclusion fails (you can catch the error, see Cerbrus' answer).
Edit:
However, if you don't want the script to halt if the inclusion fails, use the method is_readable along with file_exists, like:
if( file_exists("dbas.php") && is_readable("dbas.php") && include("dbas.php")) {
/* do stuff */
}
Simply use require:
try {
require 'filename.php';
} catch (Exception $e) {
exit('Require failed! Error: '.$e);
// Or handle $e some other way instead of `exit`-ing, if you wish.
}
Something that wasn't mentioned yet: you could add a boolean, like:
$dbasIncluded = true;
In your dbas.php file, then check for that boolean in your code. Although generally, if a file doesn't include properly, you'd want php to hit the brakes, instead of rendering the rest of the page.
file_exists("dbas.php") Is doing the checking. If it exists, then do the include.
if(file_exists("dbas.php"){
include("dbas.php")
//continue with you code here
}
Put your functionality in a function and use function_exists to check if it is there.
include ("php_file_with_fcn.php");
if (function_exists("myFunc")) {
myFunc();
// run code
} else {
echo "failed to load";
}
In your case, the incusion file would be
function db_connect() {
$user = "user";
$pass = "pass";
$host = "host";
$database = "database";
mysql_connect($host, $user, $pass);
return mysql_select_db($database);
}
and the main file:
include("db_connect.php");
if (function_exists("db_connect")) {
if (db_connect() === TRUE) {
// continue
} else {
// failed to connect (this is a different error than the "can't include" one and
// actually **way** more important to handle gracefully under great load
}
} else {
// couldn't load database code
}
Use this code instead of your code, because in your code if file is not exist in server then php errors arise and that is not good so use this code:
if(file_exists("dbas.php")) {
include_once("dbas.php");
} else {
echo"file is not found";
}
This code means if file exists on server then function include else file is not found echo.
write
echo "file is includ"
at the end of "dbas.php"
is there any any other command we can use as an alternative to exit(); in php.
Because it breaks my html code at the end of the page if the condition is not met and when script has to exit.
Or if anyone has any other idea to resolve this issue???
Thanks
Update:
html code...
<?php
if username is not in correct format
echo "Please check your username";
exit();
if Username and Password didn't match
echo "Wrong Username or Password.";
exit();
if some other condition not met
echo "Condition not met";
exit();
?>
html code continues...
Now the problem is if any of the condition is not met and the script has to exit, the html code below it, which is a whole webpage, does not display...
And please...I am not a computer geek, had a problem so asked it, but why people vote down the question??? don't understand....
You should probably wrap your code into an if statement:
<?php
if($code == 'ok'){
echo 'ok';
} else {
echo 'not ok';
}
?>
your script doesn't have to exit(), you can add statements where you want and how you want.
As the name suggests, the PHP exit() statement will cause your PHP script to exit, right there and then, and not do anything else. If you want it to carry on processing the rest of the code, just don't use exit().
Looking at your code, what you seem to be aiming for is displaying errors to the user, and then (I would guess) re-showing the form they filled in incorrectly.
Rather than just echoing the errors as soon as you discover them, why not store them into a variable, which can then be displayed at an appropriate point in the HTML? Even the most basic of scripts can benefit from a bit of basic code structure.
As an example (and I stress this is not the One True Pattern for this kind of thing), you could arrange your file something like this:
if ( /* form has been submitted */ )
{
$errors = validate_form();
if ( count($errors) > 0 )
{
display_form($errors);
}
else
{
display_success_message();
}
}
else
{
display_form();
}
function validate_form()
{
$errors = array();
// Series of if conditions, each adding a message to $errors if appropriate
return $errors;
}
function display_form($errors=array())
{
// HTML <ul> list displaying the contents of $errors, if any
// HTML for form
}
function display_success_message()
{
// HTML thanking user for a successful form submission
}