-1

The question I am asking has been asked here but was asked pretty badly and resulted in the problem not being resolved. this koneksi.php

<?php
  $host = "localhost";
  $user = "root";
  $pass = "";
  $db   = "zou";

  $con = mysqli_connect($host, $user, $pass, $db);
  if (mysqli_connect_errno()){
    echo "Koneksi gagal: " . mysqli_connect_error();
  }
?>

this is my cek_login.php

session_start();

// menghubungkan php dengan koneksi database
include 'koneksi.php';

// menangkap data yang dikirim dari form login
$username = $_POST['username'];
$password = md5($_POST['password']);


// menyeleksi data user dengan username dan password yang sesuai

   $query = mysqli_query($con, "SELECT * FROM user WHERE username='$username' AND password='$password'");
   $data = mysqli_fetch_array($query);
   $jml = mysqli_num_rows($query);
// cek apakah username dan password di temukan pada database
if($jml > 0){

   $data = mysqli_fetch_assoc($login);

   // cek jika user login sebagai admin
   if($data['level']=="admin"){

      // buat session login dan username
      $_SESSION['username'] = $username;
      $_SESSION['level'] = "admin";
      // alihkan ke halaman dashboard admin
      header("location:dashboard.php");

 
   }else{

      // alihkan ke halaman login kembali
      header("location:index.php?pesan=gagal");
   }  
}

why i can't defined the username? the detail in $username can't call.

What is the meaning of these error messages?

how do i fix them?

  • Kadir can you show us your view page? from where you are posting this data – M.Hemant Feb 21 '19 at 03:37
  • 1
    Possible duplicate of ["Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset" using PHP](https://stackoverflow.com/questions/4261133/notice-undefined-variable-notice-undefined-index-and-notice-undefined) – Paul T. Feb 21 '19 at 03:38
  • 1. Please add the form where the data's from. 2 Please post your code here, not a screenshot of your code. 3. `md5()` is not a recommended way to hash user's password. please use `password_hash()` and `password_verify()` –  Feb 21 '19 at 03:44
  • @kadir i think your username is different than your view name attribute please check – M.Hemant Feb 21 '19 at 03:49
  • ok this the change of my code – abdul kadir almasyhur Feb 21 '19 at 03:49

1 Answers1

0

Root Cause:

It because, $_POST in your case will be initialised only when you submit the form.

You are using it by default.

Solution:

Add a condition before you use $_POST ed variables.

if (isset($_POST['username'])) {
 // Your code after form is posted.
}

This will ensure that the variables are posted before use.

And avoid any errors.

Its generally a better practise to check if a variable is set before using its value.

This is absolutely fine:

$i = 0;
$i = $i + 1;

Where as

$i = $i + 1;

This will cause PHP errors as $i is not initialised.

Pupil
  • 23,834
  • 6
  • 44
  • 66