0

i have a php page which i should post some data to it like this:

$player=$_POST['player']; $age=$_POST['age']; $data=$_POST['data'];

but some times my page posts data and some times it shouldn't, when i dont post data i got Undefined index: error, is there any way to skip $_POST['data'] when no data is posted?

georg
  • 211,518
  • 52
  • 313
  • 390
Sina Nouri
  • 111
  • 3
  • 13

5 Answers5

3
$player = isset($_POST['player'])?$_POST['player']:"";
$age = isset($_POST['age'])?$_POST['age']:"";
$data = isset($_POST['data'])?$_POST['data']:"";

The isset first checks if it's defined, if yes, it assigns the variable else it assigns empty string.

Rikudou_Sennin
  • 1,357
  • 10
  • 27
2

Use simple if (isset($_POST['key'])):

$player = isset($_POST['player']) ? $_POST['player'] : '';
$age = isset($_POST['age']) ? $_POST['age'] : '';
$data = isset($_POST['data']) ? $_POST['data'] : '';

Or better, but every value to some 'refix':

<input name="Data['player']"/>

and in php just do:

if (isset($_POST['Data'])) {
     $player = $_POST['Data']['player'];
     /* ... */
}
Justinas
  • 41,402
  • 5
  • 66
  • 96
  • 1
    I didn't downvote, by why "better, put every value to some 'refix'". Why is this better? Surely you should have used "alternatively". Maybe I'm being pedantic – ʰᵈˑ Feb 09 '15 at 14:14
  • @ʰᵈˑ Because if prefix is set, than your form is sent and every other values will be set too (unless you are missing html form element, than it will not work). – Justinas Feb 09 '15 at 14:15
  • $player = $_POST['Data']['player']; i just dont get this data is not related to player so why $_POST['Data']['player']? – Sina Nouri Feb 09 '15 at 14:19
  • @SinaNouri It's not `data` from your example, it's wrapping key, that holds all information from your form. It's example from Yii framework, where all form data is inside key same as model name. Like you you have contacts form, it will be `$_POST['Contacts']['email']` / `$_POST['Contacts']['content']`... – Justinas Feb 09 '15 at 14:22
0
if(isset($_POST['DATA'])){
 $data = $_POST['DATA']
}
Epodax
  • 1,828
  • 4
  • 27
  • 32
-2
if(isset($_POST['player'])):
    $player = $_POST['player'];
endif;
Mr Pablo
  • 4,109
  • 8
  • 51
  • 104
-2

Check if data is posted

if(isset($_POST['player']))
$player=$_POST['player'];
}
if(isset($_POST['age']))
$age=$_POST['age'];
}
if(isset($_POST['data']))
$data=$_POST['data'];
}
rack_nilesh
  • 553
  • 5
  • 18