I'm having a problem with php switch function. I know it must be simple, but i'm just learning and I can't seem to find the right way to code it. This is the issue: It works fine when you click any of the options, but it sends an error msg when I first load up the page...
<body>
<?php include ('./header.php')?>
<section>
<div >
<ul>
<li><a href="./index.php?opcion=op1">Opcion 1</a></li>
<li><a href="./index.php?opcion=op2">Opcion 2</a></li>
<li><a href="./index.php?opcion=op3">Opcion 3</a></li>
</ul>
</div>
<?php
if(isset ($_GET['opcion'])) {
switch($_GET['opcion']) {
case 'op1' :
$nombre = 'Magnus Carlsen';
$posicion = '1';
$puntaje = '2840';
$img = './magnus.jpg';
break;
case 'op2' :
$nombre = 'Ian Nepomniatchi';
$posicion = '2';
$puntaje = '2812';
$img = './nepo.jpeg';
break;
case 'op3' :
$nombre = 'Ding Liren';
$posicion = '3';
$puntaje = '2760';
$img = './ding.jpg';
break;
}
}
else {
}
?>
<div >
<h3><?php echo $nombre?></h2>
<h4><?php echo $posicion?></h4>
<p><?php echo $puntaje?></p>
<div >
<img src="<?php echo $img ?>" alt="foto">
</div>
</div>
Now, I suppose the "show" div shouldn't be there... but it doesn't responde well when i move it around either...
this are the errors:
Warning: Undefined variable $nombre in C:\xampp\htdocs\dashboard\proyectos\PHP\index.php on line 53
Warning: Undefined variable $posicion in C:\xampp\htdocs\dashboard\proyectos\PHP\index.php on line 54
Warning: Undefined variable $puntaje in C:\xampp\htdocs\dashboard\proyectos\PHP\index.php on line 55 foto
CodePudding user response:
The problem is that when the form is not submitted, you do not enter your switch. that means your $nombre
, $posicion
, $puntaje
and most probably $img
are not defined. There are 2 ways to unblock yourself.
Option 1, give a default value to these variables
// here you can define your variables
$nombre = 'no number';
$posicion = 'no position';
$puntaje = 'empty';
$img = '';
if (isset ($_GET['opcion'])) {
switch ($_GET['opcion']) {
case 'op1' :
$nombre = 'Magnus Carlsen';
$posicion = '1';
$puntaje = '2840';
$img = './magnus.jpg';
break;
case 'op2' :
$nombre = 'Ian Nepomniatchi';
$posicion = '2';
$puntaje = '2812';
$img = './nepo.jpeg';
break;
case 'op3' :
$nombre = 'Ding Liren';
$posicion = '3';
$puntaje = '2760';
$img = './ding.jpg';
break;
}
} else {
}
or you can check to see if user has submitted the form and only then try to echo the variables. You can do this by surrounding the html in an if statement.
<?php if(isset ($_GET['opcion'])) { ?>
<div >
<h3><?php echo $nombre?></h2>
<h4><?php echo $posicion?></h4>
<p><?php echo $puntaje?></p>
<div >
<img src="<?php echo $img ?>" alt="foto">
</div>
</div>
<?php } ?>