need help with this. so in index.php i have a html tag

<p id = 'login_error'></p>

here(p tag) i want to print all the errors which are tested in login.php.
in login.php i create a array called $error = array(); where has all the errors.
in error_message.php iam printing all the errors.

so some how i am trying to print all the errors in index.php which are tested in login.php.
here what iam thingking, in index.php

<p id = 'login_error'> include"error_message"</p>

full code.................
-------------------------------------------- index.php------------------------------------------------

<?php
session_start();
include("connect.php");

//check, if user is loged in or not
if(isset($_SESSION['username']))
{
    //log in(member)
    echo 
    "
     YOU ARE LOGED IN
     <a href='logout.php'> logout! </a>
    ";
}
else
{
//not loged in(not member)
echo 
"
YOU ARE NOT LOG IN!
<form method='post' action='login.php'>
<strong>Member Login </strong><br/>
<p id = 'login_error'>  </p>
Username:<input name='username' type='text' id='username'><br/>
Password: <input name='password' type='password' id='password'><br/>
<input type='submit' value='Login'>
<a href='register.php'> Register! </a>
</form>
";
}
?>

---------------------------------------------------login.php-------------------------------------------------------------

<?php
session_start();
include("connect.php");

$post_username = $_POST['username'];
$post_password = $_POST['password'];

if($post_username && $post_password)
{
    $error = array();
    if(strlen($post_username) == 0 || strlen($post_password) == 0)
    {
        $errror[] = "Username and password required!";
    }
    if(strlen($post_username) > 20 || strlen($post_password) > 20)
    {
        $errror[] = "Username or Password character length is too long!";
    }
    else
    {
        //convert password to md5
        $port_password = md5($post_password);

        //query the database           /* table */
        $login = sprintf("SELECT * FROM user WHERE username='%s' AND password ='%s'", mysql_real_escape_string($post_username),mysql_real_escape_string($post_password));

        $rowcount = mysql_num_rows(mysql_query($login));
        $fieldarray= mysql_fetch_assoc(mysql_query($login));

        $id = $fieldarray['user_id'];

        if($rowcount == 1)
        {       
        //log the user in
        $_SESSION['username'] = $post_username;
        $_SESSION['user_id'] = $id;
        header('Location: index.php');
        }
        else
            $error[] = 'Incorrect username or password combination!';
    }
}
        header('Location: index.php');
        //print all errors
        foreach($error as $login_error)
        {
            echo "<p id = 'login_error'>$error</p>";
        }
?>

--------------------------------------------------error_message.php------------------------------------

<?php
/* when a user login it give a vaiable. Its for testing if user login or logout*/
session_start(); 
include("connect.php");
//print all errors
        foreach($error as $error)
        {
            echo "<p id = 'login_error'>$error</p>";
        }
?>

Recommended Answers

All 11 Replies

yes i did. i didnt explain the problem right in tht thread

Member Avatar for diafol

Did you try my method? From what I can see the question is pretty much the same:

errors identified in login page - redirect to index page - print our errors in index page

i dont know. i didnt understant what was that code doing.

in my login.php i store all error in a array call $error.

in my error_message.php file now i made a function

<?php
function output_error($error)
//print all errors
    $output = array();
        foreach($error as $error)
        {
            $output[] = '<li>'.$error . '</li>';
        }
        return '<ul>' . implode('', $output) . '</ul>';
?>
Member Avatar for diafol

You can't test for something in one page and expect the next page to remember those results unless you specifically pass data to the new page, either by url querystring, cookies or sessions. There are other methods, but those are the usual suspects.

@hwoarang69;

Here is a sample just to help you out..

## first you need to take the form out of the echo zone..
else
    {
    ## it is ok to close PHP below 
    ?>
    <!-- codes below can be pure html.. Don't let your php parser to parse something that can be directly given to the browser -->

   <!-- not loged in(not member) -->

    <h2> YOU ARE NOT LOG IN!</h2>
    <form method="post" action="login.php">
    <strong>Member Login </strong><br/>
    <p id = "login_error"> </p>
    <label>Username:</label>
    <input name="username" type="text" id="username"><br/>
    <label>Password: <label>
    <input name="password" type="password" id="password"><br/>
    <input type="submit" value="Login" name="submit">
    <a href="register.php"> Register! </a>
    </form>
   <! -- we can open or define php document tags again below to close the else curly bracket -->
   <?php
   ## this is what I am talking about.
    }
    ?>

If you take a closer look on your form codes, you will probably notice that I took it our of the echo function. Can't talk much about why?, but the idea is to not deal with too many html embedded inside the php. With this method, you can remove the entire form out of this page, and then put it in different page, save it as from.php and then just include it here, but that is out of the scope of this question.

Now, we move on to your simple form validation codes... I hope you will be working on this a little later. Otherwise this type of validation will not thrive in production server. Below is your original script as shown above. I am not going to rewrite everything for you, but I would rather give you some example and hopefully you will be able to see the logic reasoning behind all of these codes.

this is your codes.. I will be picking bits and pieces from the codes you have presented above...Looking at these codes, it is more likely to give you an undefined index error on username and password.

$post_username = $_POST['username'];
$post_password = $_POST['password'];
if($post_username && $post_password)
{
$error = array();
if(strlen($post_username) == 0 || strlen($post_password) == 0)
{
$errror[] = "Username and password required!";
}
if(strlen($post_username) > 20 || strlen($post_password) > 20)
{
$errror[] = "Username or Password character length is too long!";
}
else
{

Codes above can be minimally re-written this way

 ## We need to set our error variable to null or just empty. This is the default value. In mathematics we call this as equilibria. A condition which is ideal. In your case there is no error, until it is changed by either or all below.

 $error = "";

 ## first we need to check if the form has been submitted using the submit button as the triggering mechanism to validate our isset condition.

 if(isset($_POST['submit'])){
 ## form has been submitted, we should do some check points as laid out on your script. We validate username and password

 $post_username = $_POST['username'];
 $post_password = $_POST['password'];

 if($post_username && $post_password)
{

if(strlen($post_username) == 0 || strlen($post_password) == 0)
{
$errror .= "Username and password required!";
}
if(strlen($post_username) > 20 || strlen($post_password) > 20)
{
$errror  .= "Username or Password character length is too long!";
}

 }

else
 {
  ## put the rest of your codes here down to the last curly bracket before the else statment.


  }

  ## this is your last error 

   else
   $error .= 'Incorrect username or password combination!';

  }
}

 ## place the error or errors into session.
   # any error will be in this session error.
$_SESSION['error'] = $error;
## redirect browser
header('Location: index.php');

On your index.php, add

 session_start();

 ## check if there are any errors in the SESSION
 if(array_key_exists('error',$_SESSION) && !empty($_SESSION['error'])) {

   echo $_SESSION['error'];

 }

Do the same on other pages requiring you to show errors. The only possible problem I could see with my sample codes above is the lack of error itemization. You can easily correct it by adding some kind of delimiter, so that exploade function can be used.

For example, this

     $errror .= "Username and password required!";

Can be written with delimiter |

    $errror .= "Username and password required! |";

Now, we can use explode function to separate errors..

I hope at the very least, I made some sense out of these lenghty response.... :) I apologize for the typos.. it is because I am on wireless keyboards, when I type really, really fast ..it is not catching up on laters and words..so some of my words above are missing a letter or two, but they are readable to the point where it can make a little sense -- I believe.

.thank alot veedeo0!

Member Avatar for diafol

@vee
Do you need an unset as below to kill off repeat message on refresh?

if(array_key_exists('error',$_SESSION) && !empty($_SESSION['error'])) {
   echo $_SESSION['error'];
   unset($_SESSION['error']); //or empty the item
 }

Just skimmed.

oh YESSSSSS,,, thanks diafol... You are so cool.. :)

omg i just tierd it and its working fine! thanks alot diafol and veedeoo.

last question that is ".="?

it is called concatenating assignment operator, or "dot equals", which is pretty similar to += plus equals in java language.

for more info. read more about it Here.

But in the event where we are dealing with the items inside a loop like for, foreach, and while loops. You can do the array like this

  $thisArray = ();
 while(something is true){
 ## iterated items
 $thisArray['itemOne'] = $itemOne;
 $thisArray['itemTwo'] = $itemTwo;
 ## we can easily print the items within the array in this section, but we don't like that.
 ## so instead, we can assign it to something like my example below

 $asignedArray[] = $thisArray;

 }
  ## outside the while loop or anywhere. It can also be another page as long as you can pass it down or extend. You can do this

  foreach($asignedArray as $item){

  echo $item[0];
  echo $item[1];

  }

  ## you can also use $item['itemOne'],.. and so forth.

By following this simple system, we can easily convert anything to templating system in the likes of smarty, twigs and many others. Say, if we want to send the $thisArray to templating system. We just delete the foreach loop below and make the assignment to the template.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.