简体   繁体   中英

PHP error: Undefined Index

I'm newbie on Ajax and PHP. Decided to create index.php (using ajax) and simpan.php

<?php
include 'koneksi.php'; //conn
$target_dir="foto/";
$target_file=$target_dir.basename($_FILES['foto']['name']); //error
move_uploaded_file($_FILES['foto']['tmp_name'],$target_file); //error
$q=$db->prepare("insert into mahasiswa values
(?,?,?,?,?)");
$param=array($_POST['nim'],$_POST['nama'],
            $_POST['alamat'],$_POST['email'],
            $_FILES['foto']['name']); //error
$q->execute($param);
if($q){
    echo "OK";
}else{
    echo "fail";
}

I'm confused it has some errors:

Undefined index: foto in C:\\xampp\\htdocs\\lat_ajax204\\simpan.php on line 4

Undefined index: foto in C:\\xampp\\htdocs\\lat_ajax204\\simpan.php on line 5

Undefined index: foto in C:\\xampp\\htdocs\\lat_ajax204\\simpan.php on line 10

Fatal error: Uncaught PDOException: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'foto' cannot be null in C:\\xampp\\htdocs\\lat_ajax204\\simpan.php:11 Stack trace: #0 C:\\xampp\\htdocs\\lat_ajax204\\simpan.php(11): PDOStatement->execute(Array) #1 {main} thrown in C:\\xampp\\htdocs\\lat_ajax204\\simpan.php on line 11

I create a mysql column in mahasiswa table for foto, the type is blob. Does it make the problem? But index.php has no error at all. Thank you

Use isset() to check if the form is submitted.

http://php.net/manual/en/function.isset.php

<?php
include 'koneksi.php'; //conn
if(isset($_FILES['foto'],$_POST['nim'],$_POST['nama'],$_POST['alamat'],$_POST['email'])) {
  $target_dir="foto/";
  $target_file=$target_dir.basename($_FILES['foto']['name']); //error
  move_uploaded_file($_FILES['foto']['tmp_name'],$target_file); //error
  $q=$db->prepare("insert into mahasiswa values
  (?,?,?,?,?)");
  $param=array($_POST['nim'],$_POST['nama'],
              $_POST['alamat'],$_POST['email'],
              $_FILES['foto']['name']); //error
  $q->execute($param);
  if($q){
      echo "OK";
  }else{
      echo "fail";
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM