0

It occurs undefined index error for the first time while redirecting to the same page after login, how can I solve this problem?

Here's my code:

code on index-page

<?php
session_start();
$error = $_SESSION['error'];
$conn = mysql_connect("localhost", "root", "");
mysql_select_db("db_food", $conn);
$row = mysql_query("select * from tbl_temp order by id DESC", $conn);
$row = mysql_fetch_array($row);
$user = $row['user'];
$pass = $row['pass'];
?>

code for the page After form submission

<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
if($username =='' || $password == '') {
    $error = "Username or Password cant' be empty......";
    header("location: index.php");
} else {
    $data = mysql_query("select * from tbl_user where username='$username' && password='$password'", $conn);
    $num = mysql_num_rows($data);
    if($num==1) {
        $row = mysql_fetch_array($data);
        $_SESSION['name'] = $row['name'];
        $_SESSION['id'] = $row['id'];
        $_SESSION['user'] = $row['username'];
        exit;
    } else {
        $error= "Either Username or Password wrong!!!";
        header("location: index.php");
    }
}
$_SESSION['error'] = $error;
?>

I want to display the error message in the index page.

4
  • 1
    Please read about SQL injections and how to prevent them. Don't use SQL if you don't understand basic security principles. Commented Feb 16, 2017 at 9:54
  • 1
    On the 2nd line of your index, replace $error = $_SESSION['error']; with $error = isset($_SESSION['error']) ? $_SESSION['error'] : null; Commented Feb 16, 2017 at 9:56
  • What @still_learning says. And don't use mysql_* functions anymore. Commented Feb 16, 2017 at 11:00
  • Thank you guys ,, and specially thanks Mr. @still_learning, Commented Feb 16, 2017 at 13:01

1 Answer 1

1

check first by isset

$error = "";
if(isset($_SESSION['error'])){
  $error = $_SESSION['error'];
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.