PHP - Undefined variable: reg - Invalid argument supplied for foreach()

 
Vista:
sin imagen de perfil
Val: 396
Bronce
Ha mantenido su posición en PHP (en relación al último mes)
Gráfica de PHP

Undefined variable: reg - Invalid argument supplied for foreach()

Publicado por Robokick (156 intervenciones) el 01/09/2021 21:45:03
HOLA AMIGOS, COPIO MI CODIGO HTML Y PHP Y LUEGO EXPLICA EL PROBLEMA

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.error{
color: red;
}
</style>
</head>
<body>
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
<input type="text" name="nombre" placeholder="Nombre">
<button type="submit" name="boton">Buscar</button>

<?php foreach ($reg as $reg2): ?>
<div><?php echo $reg2['nombre']."<br>"; ?></div>
<?php endforeach; ?>


<?php if(!empty($errores)): ?>
<div class="error"><?php echo $errores; ?></div>
<?php endif;?>
</form>

</body>
</html>

************************************************************************************************

<?php

if(isset($_POST['boton'])){
$nombre=$_POST['nombre'];


$errores="";
if(empty($nombre)){
$errores= "Ingresar texto de busqueda";
}
else{
try{
$conexion= new PDO('mysql:host=localhost;dbname=base1',"root","");

}
catch(PDOException $e){
echo "error " . $e->getMessage();
die();
}


$sql="select * from alumnos where nombre like '%$nombre%'";
$registro=$conexion->prepare($sql);
$registro->execute();
$reg=$registro->fetchAll();


}

}

require 'formulario.vista.php';

?>

COMO VEN EN MI COIGO PHP TENGO DEFINIO MI VARIABLE $REG Y TRATO DE MOSTRAR EN HTML EL RESULTDO PORQUE DE LO CONTRARIO EL RESULTADO NO ME APARECE DEBAJO DEL INPUT SINO ARRIBA ENTONCES SI ME APRECEN 200 REGISTROS MI INPUT Y BOTON SE ME IRAN HASTA ABAJO

EL ERROR QUE OBTENGO ES:

Notice: Undefined variable: reg in C:\xampp\htdocs\curso_php\mirepaso\ecuador\formulario.vista.php on line 19

Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\curso_php\mirepaso\ecuador\formulario.vista.php on line 19

DONDE LINEA 19 ES:
<?php foreach ($reg as $reg2): ?>

ALGUIEN ME PODRIA AYUDAR CON LA SOLUCION POR FAVOR
MUCHAS GRACIAS
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder