Home > other >  undefined array key and don't know where that key comes from
undefined array key and don't know where that key comes from

Time:05-28

I'm following this one, https://www.androidhire.com/insert-data-from-app-to-mysql-android/

and there's an error in Step 'Upload the php script on your server', 'code for get_data.php file'

<?php

include 'DatabaseConfig.php' ;
 
 $con = mysqli_connect($HostName,$HostUser,$HostPass,$DatabaseName);
 
 
     $room = $_POST['room'];
     $time = $_POST['time'];


 $Sql_Query = "insert into GetDataTable (room,time) values ('$room','$time')";
 
 if(mysqli_query($con,$Sql_Query)){
 
 echo 'Data Submit Successfully';
 
 }
 else{
 
 echo 'Try Again';
 
 }
 mysqli_close($con);
?>

this is my code and my database table is this enter image description here

and error message is Warning: Undefined array key "room" in C:\xampp\htdocs\get_data.php on line 8

so I tried

if(isset($_POST['room']){
        $room = $_POST['room'];
    }

but this gave me Warning: Undefined variable,,,,,,,

CodePudding user response:

You need to put the if() around the whole block of code that uses $room:

<?php

include 'DatabaseConfig.php' ;
 
$con = mysqli_connect($HostName,$HostUser,$HostPass,$DatabaseName);
 
if ( isset( $_POST['room'] ) ) {
   $room = $_POST['room'];
   $time = $_POST['time'];

   $Sql_Query = "insert into GetDataTable (room,time) values ('$room','$time')";
 
   if(mysqli_query($con,$Sql_Query)){
       echo 'Data Submit Successfully';
   } else{
       echo 'Try Again';
   }
   mysqli_close($con);
}
?>
  • Related