Notice: Undefined variable but I already defined it - php

I'm having a problem and I can't find a solution. I'm getting this error "Notice: Undefined variable: id_horaire". But I defined it and I don't know how to fix that.
Here's my code :
<?php
require_once '../database.php';
if (!$_SESSION['admin']) {
header('location:login.php');
exit();
}
if(isset($_GET['id']) AND !empty($_GET['id'])) {
$id_horaireSecure = htmlspecialchars($_GET['id']);
$id_horaire = $db->prepare('SELECT * FROM runaway.horaire WHERE id = ?');
$id_horaire->execute(array($id_horaireSecure));
}
if(!empty($_POST['heure_ouverture']) AND !empty($_POST['heure_fermeture'])) {
$heure_ouverture = ($_POST['heure_ouverture']);
$heure_fermeture = ($_POST['heure_fermeture']);
$update = $db->prepare('UPDATE runaway.horaire SET heureOuverture=?, heureFermeture=?');
$update->execute(array($heure_ouverture, $heure_fermeture));
$message = "L'horaire a bien été mise à jour";
header('location:login.php');
exit();
} else {
$message = 'Les champs ne sont pas tous remplis';
}
?>
<div class="phpContainer">
<h2>Changer les horaires d'ouverture du Lundi</h2>
<div class="form col-12">
<div class="contact-form container">
<form method="post" enctype="multipart/form-data">
<div class="input-container">
<input type="text" name="heure_ouverture" class="input" value="<?=$id_horaire['heureOuverture'] ?>" />
<label for="">Heure d'ouverture</label>
<span>Heure d'ouverture</span>
</div>
<div class="input-container">
<input type="text" name="heure_fermeture" class="input" value="<?=$id_horaire['heureFermeture'] ?>" />
<label for="">Heure de fermeture</label>
<span>Heure de fermeture</span>
</div>
<input type="submit" value="Modifier l'horaire" class="boutonForm">
</form>
</div>
</div>
<br>
<?php if(isset($message)) {
echo $message;
}
?>
</div>
Thank you !
ps: I'm french, which is why some variables and text may seem strange to you

The problem is you declare $id_horaire only if this condition isset($_GET['id']) AND !empty($_GET['id']) met.
You can either give it a default value before the if, or you need to change your logic.

Related

how to popup an alert when form is submitted

I have a registration form and when people compile the form and submit it I want to show a popup, but the problem is it's not working. here is the code:
<?php
// result is when it's all good
if ($result) {
echo '<div class="vai-accedi">
<div class="vai-accedi2">
<div class="vai-accedi3">
<p>Congratulazioni! Registrazione Completata, puoi procedere ad accedere al tuo account. clicca ok per procedere</p>
Ok
</div>
</div>
</div>';
}
?>
All the code
<!-- signup backend connection -->
<?php
include 'dbcon.php';
session_start();
// error_reporting(0);
// if (isset($_SESSION['nome'])) {
// header("Location: header.php");
// }
if (isset($_POST['submit'])) {
$nome = mysqli_real_escape_string($conn,$_POST['nome']);
$cvn = mysqli_real_escape_string($conn,$_POST['cittàvn°']);
$numerodicell = mysqli_real_escape_string($conn,$_POST['numerodicell']);
$email = mysqli_real_escape_string($conn,$_POST['email']);
$password = mysqli_real_escape_string($conn,$_POST['password']);
$confpassword = mysqli_real_escape_string($conn,$_POST['confpassword']);
$password = md5($_POST['password']);
$confpassword = md5($_POST['confpassword']);
if ($password == $confpassword) {
$sql = "SELECT * FROM utenti WHERE email='$email'";
$result = mysqli_query($conn, $sql);
if (!$result->num_rows > 0) {
$sql = "INSERT INTO utenti (nome,cittàvn°, numerodicell, email, password, confpassword)
VALUES ('$nome','$cvn','$numerodicell','$email','$password','$confpassword')";
$result = mysqli_query($conn, $sql);
if ($result) {
// echo "<script>alert('Congratulazioni! Registrazione Completata, puoi procedere ad accedere al tuo account. clicca ok per procedere')</script>";
echo '<div class="vai-accedi">
<div class="vai-accedi2">
<div class="vai-accedi3">
<p>Congratulazioni! Registrazione Completata, puoi procedere ad accedere al tuo account. clicca ok per procedere</p>
Ok
</div>
</div>
</div>';
// header( "Refresh:1; url='login.php'");
$nome = "";
$cvn = "";
$numerodicell = "";
$email = "";
$_POST['password'] = "";
$_POST['confpassword'] = "";
} else {
echo "<script>alert('oops! qualcosa è andato storto.')</script>";
}
} else {
echo "<script>alert('oops! Email già registrata.')</script>";
}
} else {
echo "<script>alert('le due password non combaciano.')</script>";
}
}
?>
<!-- signup backend connection -->
<div class="registrati">
<div class="registratiinner registratiinner2">
<h1>Registrati</h1>
<form action="" class="sign-up-form" method="POST" style="width:100%;">
<div class="input-wrapper">
<input type="text" placeholder="Nome" name="nome" required>
</div>
<div class="input-wrapper">
<input type="text" placeholder="Citta,Via,n°" required name="cittàvn°">
</div>
<div class="input-wrapper">
<input type="text" placeholder="Numero di Cellulare" required name="numerodicell">
</div>
<div class="input-wrapper">
<input type="email" placeholder="Email" required name="email">
</div>
<div class="input-wrapper">
<input type="password" placeholder="Crea una Nuova Password" required name="password">
</div>
<div class="input-wrapper">
<input type="password" placeholder="Conferma Password" required name="confpassword">
</div>
<div class="accetti">
<p style="font-size: 1.8rem; margin-top: 0;">Inviando accetti Termini & Condizioni</p>
</div>
<button type="submit" class="contact-button" style="border-radius: .5rem;" name="submit" type="submit">Registrati</button>
</form>

avoid records with the same data

by means of an if attempt that can not be created two records with the same name, it does not work and you can create a record with a dupiclate name
this is the controller
include_once 'model/solucion.php';
public function Guardar()
{
$this->model->Duplicado($_POST['Nombre']);
$name = $this->model->resultado2['Nombre'];
if($name == $_POST['Nombre']){
die("No se puede crear una solucion con el mismo nombre");
}else{
$solucion = new solucion();
$solucion->id = $_REQUEST['id'];
$solucion->Nombre = $_REQUEST['Nombre'];
$solucion->Tipo = $_REQUEST['Tipo'];
$solucion->Descripcion = $_REQUEST['Descripcion'];
$solucion->Pagina = $_FILES['Pagina']['name'];
}
header("Location: index.php");
}
this is the model
public $resultado2;
public function Duplicado($Nombre)
{
try {
$stm = $this->pdo->prepare("SELECT * FROM fallas WHERE Nombre = '$Nombre'");
$stm->execute();
$res=$stm->fetch(PDO::FETCH_ASSOC);
$this->resultado2 = array();
$i = 0;
foreach ($res as $row)
{
$this->resultado2[$i]['id'] = $row['id'];
$this->resultado2[$i]['Nombre'] = $row['Nombre'];
$this->resultado2[$i]['Tipo'] = $row['Tipo'];
$this->resultado2[$i]['Descripcion'] = $row['Descripcion'];
$this->resultado2[$i]['Pagina'] = $row['Pagina'];
$i++;
}
} catch (Exception $ex) {
die($e->getMessage());
}
}
this is the view
<ol class="breadcrumb">
<li>Inicio</li>
<li class="active"><?php echo $solucion->id != null ?
$solucion->Nombre : 'Nueva Solución'; ?></li>
</ol>
<form id="frm-alumno" action="?c=solucion&a=Guardar" method="post" enctype="multipart/form-data">
<input type="hidden" name="id" value="<?php echo $solucion->id; ?>" />
<div class="form-group">
<label>Nombre</label>
<input type="text" name="Nombre" value="<?php echo $solucion->Nombre; ?>" class="form-control" placeholder="Ingrese su nombre" required>
</div>
<div class="form-group">
<label for="exampleFormControlSelect1">Tipo de fallo</label>
<select class="form-control" id="exampleFormControlSelect1" name="Tipo" value="<?php echo $solucion->Tipo; ?>">
<option value="software">software</option>
<option value="hardware">hardware</option>
<option value="red">red</option>
</select>
</div>
<div class="form-group">
<label>Descripcion</label>
<textarea type="text" name="Descripcion" value="<?php echo $solucion->Descripcion; ?>" class="form-control" rows="10" cols="40" required>
</textarea>
</div>
<div class="form-group">
<label>Pagina.php</label>
<input type="file" name="Pagina" value="<?php echo $solucion->Pagina; ?>" >
</div>
<div class="form-group">
<label >Imagenes</label>
<input type="file" class="form-control" id="archivo[]" name="archivo[]" multiple="" >
</div>
<hr />
<br>
<div class="text-right">
<button class="btn btn-success">Guardar</button>
</div>
What do I have to change in the controller to avoid creating duplicate records with the same name?
You need to pass the array and check whether this is empty or not . Check below for the code and run it and let me know if you get any error .
public function Duplicado($Nombre)
{
try{
$stm = $this->pdo->prepare("SELECT * FROM fallas WHERE Nombre = '$Nombre'");
$stm->execute();
$res=$stm->fetch(PDO::FETCH_ASSOC);
return $res;
}catch (Exception $ex) {
die($e->getMessage());
}
}
include_once 'model/solucion.php';
public function Guardar()
{
$name = $this->model->Duplicado($_POST['Nombre']);
//$name = $this->model->resultado2['Nombre'];
if(!empty($name)){
die("No se puede crear una solucion con el mismo nombre");
}else{
$solucion = new solucion();
$solucion->id = $_REQUEST['id'];
$solucion->Nombre = $_REQUEST['Nombre'];
$solucion->Tipo = $_REQUEST['Tipo'];
$solucion->Descripcion = $_REQUEST['Descripcion'];
$solucion->Pagina = $_FILES['Pagina']['name'];
}
header("Location: index.php");
}

PHP PDO Login return boolean : false

I've created a login script where I am simply trying to match the email and password that is passed through my login form, create a session and pass through session variables and redirect the user to his account's page. This is returning bool(false)...
When registering a user I encrypt the password using the PHP password_hash method. However when I try to login my statement is returned as false and to be fair I don't know what I am doing wrong, perhaps I'm decrypting the password incorrectly, I'm not sure.
When I tried to debug it. Can't find out why it's happening.
Any help or ideas greatly welcomed and appreciated, thank you in advance.
Here is my script :
class Auth.php
public function login($db, $email, $mdp, $remember = false)
{
$user = $db->query('SELECT * FROM client WHERE (email = :email) AND confirmed_at IS NOT NULL ', ['email' => $email])->fetch(PDO::FETCH_OBJ);
/*var_dump( password_verify($mdp,($user->mdp)));*/
print_r($db->errorInfo());
if ($user && password_verify($mdp,($user->mdp)))
{ $this->connect($user);
if ($remember) {
$this->remember($db, $user->id_clt);
} //for cookie key
return $user;
} else {
return false;
}
}
login.php
<?php
require 'inc/bootstrap.php';
$auth = App::getAuth();
$db = App::getDatabase();
$auth->connectFromCookie($db);
if($auth->userLogged()){
App::redirect('account.php');
}
if(!empty($_POST) && !empty($_POST['email']) && !empty($_POST['mdp'])){
$user = $auth->login($db, $_POST['email'], $_POST['mdp'], isset($_POST['remember']));
$session = Session::getInstance();
var_dump($user);
if($user){
$session->setFlash('success' , 'Vous êtes maintenant connecté');
App::redirect('account.php');
}else{
$session->setFlash('danger', 'Identifiant ou mot de passe incorrecte');
}
}
?>
<?php require 'inc/header2.php'; ?>
<h1 align="center"> Se connecter </h1>
<form method="POST" action="" autocomplete="on">
<div class="form-group" align="center">
<label for="email">Email</label>
<input id="email" name="email" type="email" class="form-control"/>
</div>
<div class="form-group" align="center">
<label for="mdp" >Mot de passe (J'ai oublié mon mot de passe)</label>
<input id="mdp" name="mdp" type="password" class="form-control"/>
</div>
<div class="form-group" align="center">
<label>
<input type="checkbox" name="remember" value="1"> Se souvenir de moi
</label>
<button type="submit" name="forminscription" class="btn btn-primary">Se connecter</button>
</div>
<?php require 'inc/footer.php'; ?>

How to change div content in PHP?

I want to change the div's id intFrom. Content after inserting data to the database, I want the code not just echo ¡Enhorabuena!...
But replace the form with ¡Enhorabuena! I maybe, I could replace the form using AJAX.
Here is the code:
HTML
<form method="post" action="">
<div>
<select value="genero" name="genderselect" id="genero" required="required" autofocus="autofocus">
<option value="none" selected>- Selecciona Género - </option>
<option value="Mujer">Mujer</option>
<option value="Hombre">Hombre</option>
</select>
<input type="text" id="name" name="name" value="" placeholder="Nombre completo" required="required" autofocus="autofocus" />
<input type="email" id="email" name="email" value="" placeholder="Correo electrónico" required="required" />
</div>
<div>
<div class="infForm img">
<img src="http://www.miraqueguapa.com/Landings/General/img/biotherm.png" alt="Imagen Crema Aquasource Biotherm" class="biotherm">
</div>
<div class="infForm text">
<div class="legal">
<input type="checkbox" id="cblegales" value="1" name="cblegales" required="required" autofocus="autofocus">
<p>He leído y acepto la <a class="enlace_pp" href="http://www.miraqueguapa.com/content/5-privacidad-proteccion-datos" target="_blank">política de privacidad</a></p>
</div>
<input type="submit" value="ENVIAR DATOS" name="submit_form" style=" background-color: #DF2848;border: none;border-radius: 0px;color: white;width: 200px;float: right;padding-left: 50px;cursor: pointer;margin-top: -5px;" />
</div>
</div>
</form>
</div>
PHP
<?php
if (isset($_POST['submit_form'])) {
include 'connection.php';
$name=$_POST["name"];
$email=$_POST["email"];
$gender=$_POST["genderselect"];
if($gender=="none"){
echo"</br>";
echo"por favor selecciona nuestro género";
$link = null;
}
else{
$i=0;
$statement = $link->prepare("select email from webform where email = :email");
$statement->execute(array(':email' => "$email"));
$row = $statement->fetchAll();
foreach($row as $key) {
$i=$i+1;
}
if ($i !=0) {
echo" Este correo electrónico ya está registrado";
$link = null;
}
else{
$statement = $link->prepare("INSERT INTO webform(name, email, gender)
VALUES(:name, :email, :gender)");
$statement->execute(array(
"name" => "$name",
"email" => "$email",
"gender" => "$gender"
));
$link = null;
echo"¡Enhorabuena!"."<br/>";
echo"Tus datos se han enviado correctamente. A partir de ahora recibirás cada semana las últimas novedades y las mejores ofertas en Cosmética de las marcas más prestigiosas del mercado.";
}}}
?>
You need to add simple if else statement.
if (isset($_POST['submit_form'])) {
// Your code after form get submitted.
}
else {
// Show default form.
}
Just load your HMTL Code in to your PHP as a kind of "Template" with file_get_contents(__DIR__ . "Path/To/Your.html"); in to a variable and do a simple str_replace('id="your_element_id"', 'id="replace_id"', $template_variable); and echo your Template after if you just want to replace an ID.
If you want to change something within the Form, do it as i said above with str_replace('tag_you_are_looking_for', 'should_be_replaced_with', $template_variable);

Error in login Form

When i try to do log in it always appear: "El usuario o contraseña es incorrecto", i dont know the problem.
I think i have done something bad when i was tipping the code.
Here i leave the code:
Acceso.php
<?php
session_start();
$titulo = "Acceso al panel";
include 'inc/header.php';
if($_SESSION['Logueado'] == TRUE) {
header('Location: funciones/panel.php');
}else{
?>
<html>
<center>
<form method="POST" action="funciones/panel.php">
<div class="form-group">
Nombre: <input type="text" name="nombre"></input>
<hr>
Contraseña: <input type="password" name="pass"></input>
<hr>
<input type="submit" name="enviar" value="Acceso"></input>
</div>
</form>
</center>
</html>
<?php
include 'inc/footer.php';
}
?>
The next step: panel.php
<?php
session_start();
include 'inc/header.php';
include 'panel_funciones.php';
$usuario = $_POST["nombre"];
$pass = $_POST["pass"];
try {
$bd = new PDO("mysql:host=localhost;dbname=b9_16267033_1","b9_16267033","123456");
$bd->query("SET NAMES 'utf8'");
} catch (Exception $e){
echo "No se ha podido conectar";
exit;
}
try{
$sql= "SELECT usuario, pass FROM usuarios WHERE usuario='$usuario' and pass='$pass'";
}catch(Exception $e){
echo "Error en consulta";
exit;
}
$iniciosesion=mysql_query($sql);
$contar = mysql_num_rows($iniciosesion);
// AQUI COMIENZA COMPROBACIÓN
if ($contar == 1) {
$_SESSION['Logueado'] = TRUE;
panel();
}
else{
echo "El usuario o contraseña es incorrecto";
}
include 'inc/footer.php';
?>
The function: panel_funciones.php
<?
$user = "Javier";
function panel(){
session_start();
echo "<center><h3>Bienvenido al Panel de Control</h1></center></h3></center>";
echo '<form action="logout.php" method="post">';
echo '<input type="submit" value="salir"></form>';
echo '<center>
<h4>Añadir Imagen</h4><hr>
<form method="POST" action="accion.php">
<div class="form-group">
Nombre: <input type="text" name="titulo"></input>
Link a Imagen: <input type="text" name="link"></input>
<input type="submit" name="enviar" value="Enviar"></input>
</div>
</form>
<center>';
echo '
<h4>Eliminar Imagen</h4><hr>
<form method="POST" action="accion2.php">
Escribe link <input type="text" name="imagen"></input>
<input type="submit" name="enviar2" value="Enviar"></input>';
}
?>
Thanks for your help, im trying to learn so from time to time i need to ask some questions.
Great job using PDO.
But i assume u forgot to check which paremeters take mysql_query :
U're using a PDOstatement instead of a string.
panel.php
...
$sql=$bd->query("SELECT usuario, pass
FROM usuarios
WHERE usuario='$usuario' and pass='$pass') ");
}
catch(Exception $e){
echo "Error en consulta";
exit;
}
// Continue to use PDO instead depreciated functions :'(
// Using fetchAll() & count instead
$iniciosesion=mysql_query($sql);
$contar = mysql_num_rows($iniciosesion);
.Move these 2 last lines into the last try & replace them by :
$iniciosesion = $bd->query($sql);
$result = $iniciosesion->fetchAll();
$contar = count($result);
Acceso.php
u missed <html> tags in ur main page.
<?php session_start(); ?>
<html>
<head></head>
<body>
<?php
...
//Then close body & html close at the end of your file.
Source :
PHP.net : PdoStatement::Fetchall
PHP.net mysql_query

Categories