-
help with class
I set up a class as a trial. I have 7 files in my project right now. I want to make them into 2 files. an index file and a class_lib file. So I set up my first class as a trial and it seems to be working, but there is a problem in my code. I don't get any errors right now, but what I think should happen isn't happening. I have a form that asks your name, when you put it in and press submit, it ads the name to a list. All is good. So now I want to add some validation. So I set up an error class as a test run.
Code:
class error {
var $error = "You must put in a name";
var $good = "good work, name has been entered";
function myError(){
$pattern = '/[A-Za-z]+/';
if(isset($_POST['go']) && !empty($_POST['name']) && preg_match($pattern, $_POST['name']))
{
return $this->good;
}
else
{
return $this->error;
}
}
}
my issue is that when I run the index page to view the form, the $error code is already visible in the div. It doesn't wait for me to put in a name or to match the $pattern. What is wrong with my logic here? I am calling the class in my index like this
Code:
<div>
<?php
$errorCode = new error();
echo $errorCode->myError();
?>
</div>
thanks for your help
-
You could instantiate the Error Object after the $_POST['go'] is set (the bottom part).
PHP Code:
Class Error
{
var $error = "You must put in a name";
var $good = "good work, name has been entered";
function myError()
{
$pattern = '/[A-Za-z]+/';
if(!empty($_POST['name']) && preg_match($pattern, $_POST['name']))
{
return $this->good;
}
else
{
return $this->error;
}
}
}
PHP Code:
<div>
<?php
if (isset($_POST['go']))
{
$errorCode = new error();
echo $errorCode->myError();
}
?>
</div>
It is Echoing out something cause you have a condition that will either Output $good or $bad.
So you should only echo the object once the Submit $_POST['go'] is placed.
-
I tried that and it does not work. I do not understand why. I have it set up to display an error if you do not put in a name and to display a success code if you do put in a name. But when I push the submit button, nothing shows up.
-
Is it refreshing the same page or going to another page?
Are you on PHP5?
-
The form is on an index page. The code that I am working on is in a file I called error.php. Then I used a php include in the header of the index to include the error.php. the action of the form is in a file I called insert.php. So when you push the submit button, it goes to the action page, then I have a line in there that brings me back to the index page like this
Code:
$name = $_POST['name'];
$sql="INSERT INTO mytable (names) VALUES ('$name')";
header("Location: index.php");
I don't understand the difference between the versions of php. So I can't tell you if it's 1 - 5 or not