-1

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

1 Answers1

0

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";
  }
}
swordsecurity
  • 385
  • 3
  • 15
  • thankyou, no more line of error. but data doesn't inserted to database.. can you fix it? – Satria Chandra Kusuma Apr 24 '16 at 13:03
  • Hi Satria, the code snippet above is a direct answer to your question regarding undefined index errors. Why the data in not inserted in the database is out of the scope of the index errors problem. – swordsecurity Apr 24 '16 at 13:11
  • You can ask a new question and post your HTML/PHP code to see if anyone can help you with the database problem. – swordsecurity Apr 24 '16 at 13:13